1

I have to upload images, audio, documents. I'm using Alamofire to upload. Everything is uploaded including gallery images like screenshots, but pictures taken from camera are not getting uploaded. Here's my code:

func requestUploadFileWithMultipart(connectionUrl: String, param : [String: AnyObject], filePath: String?, _ callBack: @escaping (_ data: DataResponse<Any>?, _ error:Error?) -> Void) {

    let URLString  = MainURL + connectionUrl

    Alamofire.upload(multipartFormData: { multipartFormData in
        for (key, value) in param {
            let stringValue = "\(value)"
            multipartFormData.append(stringValue.data(using: String.Encoding.utf8)!, withName: key)
            print("Key: \(key), Value: \(stringValue)")
        }

        if filePath != "" {
            do {
                var fileData = try Data(contentsOf: URL(string: filePath!)!)
                let ext = URL(fileURLWithPath: filePath!).lastPathComponent.components(separatedBy: ".").last
                let mime = filePath?.mimeTypeForPath()
                let fileName = "\(Date().timeIntervalSince1970)".components(separatedBy: ".").first
                multipartFormData.append(fileData, withName: "file", fileName: "\(fileName ?? "file").\(ext ?? "")", mimeType: mime ?? "")
            } catch {
                print("error loading file in multipart")
            }
        }

    }, to:URLString) { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            })

            upload.responseJSON { response in
                print(response.result.value as Any)



                callBack(response, nil)
            }

        case .failure(let encodingError):
            print(encodingError)

            callBack(nil, encodingError)
        }
    }
}
Krutika Sonawala
  • 1,065
  • 1
  • 12
  • 30
  • what does that mean? you have some error? app crash or something else happens? – Lu_ Jul 12 '19 at 10:32
  • 1
    If everything else is uploading fine using your code then I suspect the image format is the culprit. Maybe your backend doesn't support HEIF format. try converting the image to JPG/PNG then try to upload. – Sahil Manchanda Jul 12 '19 at 10:45
  • @SahilManchanda I'm converting picked image to .png and saving it into docs directory. After that I'm uploading it. – Krutika Sonawala Jul 16 '19 at 06:53
  • @KrutikaSonawala, glad that you have found the reason. I suggest you to investigate further. There are now two cases 1. Connection failure (which is less likely) 2. MAX Upload File Size (Ask your backend dev that how many MBs are allowed for file upload) – Sahil Manchanda Jul 16 '19 at 09:17
  • yes. I have asked but they said that there's no limit for the files. So I was wondering why is this happening. But compressing it worked. so I didn't bother to ask them to change. – Krutika Sonawala Jul 17 '19 at 05:29

2 Answers2

1

Image compression worked for me. May be large files were no uploading.

Krutika Sonawala
  • 1,065
  • 1
  • 12
  • 30
0

Please try below code, I am using this code in my one of project. But make sure that API is suitable for multipart uploading.

Alamofire.upload(multipartFormData: {
        multipartFormData in
        if let img =  image {
            if let imageData = img.jpegData(compressionQuality: 0.4) {
                multipartFormData.append(imageData, withName: "cmt_img", fileName: "\(Date()).jpg", mimeType: "image/jpg")
            }
        }
        do {

            let theJSONData = try JSONSerialization.data(withJSONObject: param, options: JSONSerialization.WritingOptions(rawValue: 0))
            multipartFormData.append(theJSONData, withName: "data")
        } catch {}
    },usingThreshold: 0 ,to: baseURL + URLS.AddComment.rawValue, headers: appDelegate.headers, encodingCompletion: {
        encodingResult in switch encodingResult {

        case .success(let upload, _, _):
            upload.responseObject(completionHandler: { (response: DataResponse<AddCommentData>) in

                SVProgressHUD.dismiss()
                if (response.result.value != nil) {
                    showAlert(popUpMessage.uploadingSuccess.rawValue)
                }
                else {
                    showAlert(popUpMessage.someWrong.rawValue)
                }
            })

            break

        case .failure(let encodingError):
            SVProgressHUD.dismiss()
            print(encodingError)
            break
        }
    })
}
Pratik Patel
  • 1,393
  • 12
  • 18