Nermin Sehic
Nermin Sehic

Reputation: 612

Alamofire request body nil when uploading image using multipartFormData

I seem to have a problem regarding image upload and passing parameters using Alamofire. I have a quite simple function for multipart data which looks like:

sessionManager.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            print("\(value)")
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }
        multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "document", mimeType: "image/png")

    }, to: baseURL + "/documents", encodingCompletion: { (result) in
        switch result{
            case .success(let upload, _, _):
                upload.validate().responseJSON { response in
                    print("Succesfully uploaded")

                }
            case .failure(let error):
                print("Error in upload: \(error.localizedDescription)")

            }
    })

I have OAuth2Handler which i've implemented for headers and authorisation and it works for all other requests. I have also tried to implement this without wrapper using Alamofire object directly but still no luck. When I inspect the request i notice that httpBody is always nil, which corresponds to error I get from the server and the message says that I do not pass required parameters.

Upvotes: 4

Views: 1334

Answers (1)

Nikunj Kumbhani
Nikunj Kumbhani

Reputation: 3924

This is Working for me Swift 4

func callPostApiImage(api:String, parameters:[String:AnyObject]?,image:UIImage,Name:String, mime_type:String = "image/jpg",  complition:@escaping (AnyObject)->Void){

    // Encode Data
    let base64EncodedString = toBase64EncodedString(toJsonString(parameters: parameters!))

    let File_name = "image_" + String(arc4random()) + ".jpg"

    Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append(UIImageJPEGRepresentation(image, 0.5)!, withName: Name, fileName: File_name, mimeType: mime_type)
        multipartFormData.append(base64EncodedString.data(using: String.Encoding.utf8)!, withName: "jsondata")

    }, to:api){ (result) in

        switch result {

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

            upload.uploadProgress(closure: { (progress) in

                print(progress)

            })

            upload.responseJSON { response in

                print(response.result)

            }

        case .failure(let encodingError):

            print("",encodingError.localizedDescription)
            break
        }
    }
}

// Base64EncodedString
func toBase64EncodedString(_ jsonString : String) -> String
{
    let utf8str = jsonString.data(using: .utf8)

    let base64Encoded = utf8str?.base64EncodedString(options: [])

    return base64Encoded!
}

Upvotes: 1

Related Questions