Krutika Sonawala
Krutika Sonawala

Reputation: 1155

Not able to upload camera images using Almofire multipart

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)
        }
    }
}

Upvotes: 2

Views: 447

Answers (2)

Krutika Sonawala
Krutika Sonawala

Reputation: 1155

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

Upvotes: 2

Pratik Patel
Pratik Patel

Reputation: 1421

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
        }
    })
}

Upvotes: 0

Related Questions