Using Alamofire and multipart/form-data

Viewed 5233

I'm unable to approach the API that has been offered to me in the proper way for it to give me the response I'm looking for. I've been using Swift and Alamofire for a while but this is the first time I've to upload images using multipart/form-data. I'm able to upload images using Postman but I'm unable to get the same message send out by my application using the Alamofire framework.

My Postman screenshot

My Swift code:

func postFulfilWish(wish_id: Int, picture : UIImage, completionHandler: ((AnyObject?, ErrorType?) -> Void)) {

    var urlPostFulfilWish = Constant.apiUrl;
    urlPostFulfilWish += "/wishes/";
    urlPostFulfilWish += String(wish_id);
    urlPostFulfilWish += "/fulfill/images"  ;

    let image : NSData = UIImagePNGRepresentation(UIImage(named: "location.png")!)!

    Alamofire.upload(.POST, urlPostFulfilWish, headers: Constant.headers, multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(data: image, name: "file")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    //This is where the code ends up now
                    //So it's able to encode my message into multipart/form-data but it's not doing it in the correct way for the API to handle it
                    debugPrint(response)
                }
            case .Failure(let encodingError):
                print(encodingError)
            }
        }
    )
}
4 Answers

I recently got a 404 from the server when posting a multipart request along with parameters in the body. I was using a UIImagePickerController (the delegate for which returns a UIImage) and I then sent up the PNG representation of it.

This only occurred for files that were JPEG on disk. Strangely this issue seems to only affect multipart requests that also had parameters in the body. It worked fine when the API endpoint didn't require anything else.

My guess is that there is something weird going on along the line of JPEG -> UIImage -> PNG representation that results in some sort of problem which oddly only seems to manifest itself in multipart requests that also have parameters in the body. Might be some special characters in there that makes the server not recognise the request and just return a 404.

I ended up fixing it by sending up the UIImageJPEGRepresentation of the selected image instead of UIImagePNGRepresentation, and no such errors.

I believe the question is outdated already but for as long as there is no answer accepted try the following:

multipartFormData.appendBodyPart(data: imageData, name: "name", fileName: "filename", mimeType: mimeType)
Related