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

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


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 UploadRequestuploadRequest.responseJSON(completionHandler: completionHander)


This Is work for me Using Swift 4.2 Please try this

let url = "http://google.com" /* your API url */let headers: HTTPHeaders = [    /* "Authorization": "your_access_token",  in case you need authorization header */    "Content-type": "multipart/form-data"]Alamofire.upload(multipartFormData: { (multipartFormData) in    for (key, value) in parameters {        multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)    }        if let data = imageData{        multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")    }    }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in    switch result{    case .success(let upload, _, _):        upload.responseJSON { response in            print("Succesfully uploaded")            if let err = response.error{                onError?(err)                return            }            onCompletion?(nil)        }    case .failure(let error):        print("Error in upload: \(error.localizedDescription)")        onError?(error)    }}


This how I upload images and videos from a swift 5 app with Alamofire 5.

Images

    /**     Send Image to server     */    func Post(imageOrVideo : UIImage?){      let headers: HTTPHeaders = [        /* "Authorization": "your_access_token",  in case you need authorization header */        "Content-type": "multipart/form-data"    ]        AF.upload(            multipartFormData: { multipartFormData in                multipartFormData.append(imageOrVideo!.jpegData(compressionQuality: 0.5)!, withName: "upload_data" , fileName: "file.jpeg", mimeType: "image/jpeg")        },            to: "http://ip.here.--.--/new.php", method: .post , headers: headers)            .response { resp in                print(resp)                       }}

You can create a temporary resource and use the temporary url (good for videos):

/** Send video to server */func PostVideoUrl(url : URL){    let headers: HTTPHeaders = [        "Content-type": "multipart/form-data"    ]            AF.upload(        multipartFormData: { multipartFormData in            multipartFormData.append(url, withName: "upload_data" , fileName: "movie.mp4", mimeType: "video/mp4")    },        to: "http://ip.here.--.--/newVideo.php", method: .post , headers: headers)        .response { resp in            print(resp)    }}