Rutger Huijsmans Rutger Huijsmans - 9 days ago 7
Swift Question

Using Alamofire and multipart/form-data

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
case .Failure(let encodingError):


In case it is not already answered, recently I had the same problem using Alamofire to upload an Image using form-data.

I was able to upload the image using Postman exactly as it's shown in this post, but no able to do it using Alamofire in my app.

You need to check two things, first of all, the name of the file that the server is expecting, and second the method used to append the body part in the multipartFormData closure.

This two methods were not working in my case -

multipartFormData.appendBodyPart(data: imageData, name: "file")

this one neither

multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: name)

But on this one worked splendid -

multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: "file.jpeg", mimeType: "image/jpeg")

The problem basically is that the server can't find the file with the expected name.

I hope this help someone to save time wondering why it's not working.