Alamofire Multiform Upload Image with Parameters

雨燕双飞 提交于 2019-12-11 09:02:30

问题


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.


回答1:


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

    }


来源:https://stackoverflow.com/questions/55393342/alamofire-multiform-upload-image-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!