Upload files with parameters from multipartformdata using alamofire 5 in ios swift

Diaa SAlAm picture Diaa SAlAm · Mar 20, 2019 · Viewed 13.3k times · Source

I am trying upload files with parameters (multipartformdata) but i can't do it with new version Alamofire 5, if you have some experience with Alamofire 5 please share it with me.

 func uploadPluckImage(imgData : Data, imageColumnName : String,  url:String,httpmethod:HTTPMethod,completionHandler: @escaping (NSDictionary?, String?) -> ()){
    let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""
    let authorization = ["Authorization" : "Bearer \(token)"]
    let parameters: Parameters?
    parameters = [
        "garbageCollector": 0,
        "stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",
        "delete_file" : ""
    ]
    let headers : HTTPHeader?
    headers = ["Authorization" : "Bearer \(token)"]
    let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"


    AF.upload(multipartFormData: { (multipart: MultipartFormData) in
        let imageData = self.firstImage.image?.jpegData(compressionQuality: 0.7)
            multipart.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")

        for (ker, value) in parameters!{
            multipart.append(value as! String).data(using: .utf8)!, withName: key)
        }
    },usingThreshold: UInt64.init(),
       to: imageURl,
       method: .post,
       headers: headers,
       encodingCompletion: { (result) in
        switch result {
        case .success(let upload, _, _):
            upload.uploadProgress(closure: { (progress) in
              print("Uploading")
            })
            break
        case .failure(let encodingError):
            print("err is \(encodingError)")
                break
            }
        })
}

Answer

Ajay Singh Mehra picture Ajay Singh Mehra · Mar 27, 2019

Upload method slightly changed in Alamofire 5

func upload(image: Data, to url: Alamofire.URLRequestConvertible, params: [String: Any]) {
    AF.upload(multipartFormData: { multiPart in
        for (key, value) in params {
            if let temp = value as? String {
                multiPart.append(temp.data(using: .utf8)!, withName: key)
            }
            if let temp = value as? Int {
                multiPart.append("\(temp)".data(using: .utf8)!, withName: key)
            }
            if let temp = value as? NSArray {
                temp.forEach({ element in
                    let keyObj = key + "[]"
                    if let string = element as? String {
                        multiPart.append(string.data(using: .utf8)!, withName: keyObj)
                    } else
                        if let num = element as? Int {
                            let value = "\(num)"
                            multiPart.append(value.data(using: .utf8)!, withName: keyObj)
                    }
                })
            }
        }
        multiPart.append(image, withName: "file", fileName: "file.png", mimeType: "image/png")
    }, with: url)
        .uploadProgress(queue: .main, closure: { progress in
            //Current upload progress of file 
            print("Upload Progress: \(progress.fractionCompleted)")
        })
        .responseJSON(completionHandler: { data in
            //Do what ever you want to do with response
        })
}

Hope this will help you

EDIT: In case you don't quite get the above, here is an expansion:

let uploadRequest: UploadRequest = AF.upload(multipartFormData: multipartFormData, with: ...)
let completionHander: (AFDataResponse<Any>) -> Void) = { result in
    //Do what ever you want to do with response, which is a DataResponse<Success, AFError>
}
// Adds that completion hander to the UploadRequest
uploadRequest.responseJSON(completionHandler: completionHander)