简体   繁体   中英

Alamofire Multiform Upload Image with Parameters

I'm using Alamofire to upload image on server, this method working fine and I have already used in many projects.

I have used following code to upload image on my server using multiform data.

Alamofire.upload( multipartFormData: { multipartFormData in

    for (key, value) in parameters {
        if let data = (value as! String).data(using: .utf8) {
            multipartFormData.append(data, withName: key)
        }
    }

    let imageData = image?.pngData()

    multipartFormData.append(imageData!, withName: "profile_image", fileName: "profileImage", mimeType: "")

}, to: getURL(.addProfile), headers: getHeaders(), encodingCompletion: { encodingResult in

    switch encodingResult {

    case .success(let upload, _, _):

        upload.response(completionHandler: { (defaultDataResponse) in

            guard let httpResponse = defaultDataResponse.response else {
                completion(nil, defaultDataResponse.error)
                return
            }

            if httpResponse.statusCode == 200 {

                do {

                    let genericModel = try JSONDecoder().decode(ProfileImageModel.self, from: defaultDataResponse.data!)
                    completion(genericModel, nil)

                } catch {

                    completion(nil, error)
                }

            } else {
                completion(nil, defaultDataResponse.error)
            }
        })

    case .failure(let encodingError):
        completion(nil, encodingError)
    }
})

This works fine.

My issue is here, where extra parameter passing in api.

for (key, value) in parameters {
    if let data = (value as! String).data(using: .utf8) {
        multipartFormData.append(data, withName: key)
    }
}

Above code will convert string value to data and append to multipartFormData . And it's works for following type of request structure.

{
    "first_name": "ABC",
    "last_name": "XYZ",
    "bio": "iOS Developer"
}

What to do when I have following type of request structure?

{
    "first_name": "ABC",
    "last_name": "XYZ",
    "bio": "iOS Developer"
    "location": {
        "full_address": "My Location",
        "latitude": "23.0000",
        "longitude": "76.0000"
    }
}

Please help to achieve this.

Use this function

 func requestUploadImage(_ strURL : String, imageData : Data? ,params : [String : AnyObject]?, headers : [String : String]?, success:@escaping (NSDictionary) -> Void, failure:@escaping (Error) -> Void){
//        let  params = ["id": "101", "name": "Navin", "timezone": "2018-07-26  03:17:06" , "image": imageData] as [String : AnyObject]
  //
        //  CommonMethodsModel.showProgrssHUD()
    let url = URL(string: baseURL + strURL)!
    let parameters = params //Optional for extra parameter

        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imageData!, withName: "image",fileName: "file.jpeg", mimeType: "image/jpeg")
            print(imageData , params)
            for (key, value) in parameters! {
                multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
            } //Optional for extra parameters
        },
                 usingThreshold: UInt64.init(),         to:url, method: .post)
        { (result) in
//             CommonMethodsModel.HidePrgressHUD()
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (progress) in
                    print("Upload Progress: \(progress.fractionCompleted)")
                })

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

                    success(response.result.value as! NSDictionary )
                }

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM