Search code examples
iosswiftxcodeafnetworkingalamofire

Alamofire 4 File Upload Parameter issue


Plese have a look at the pic here from postman POSTMAN success result but the code does not run I am missing something please help me out

 var parameters = [String: String]()
        parameters = [
            "profile_image": "imagefile"
        ]

        let headers: HTTPHeaders = [
            "Accept": "application/json"
        ]

        let url = "http://******/public/api/v1/profile/update-picture?api_token=" + "aySlC26ZTHtlnS0lhUpdghxkd9gKJBLXLYFUO2Jidmiisoka9iFIicwRIZFx"
        let completeUrl = URL(string:url)!

        let imageData = UIImageJPEGRepresentation(chosenImage!, 1)
        print ("image data:: \(imageData)")
        print ("chosenImage:: \(chosenImage)")

//        Alamofire.upload(imageData!, to: completeUrl).response { response in
//            print (response)
//        }

        Alamofire.upload(
            multipartFormData: { 
                multipartFormData in
                multipartFormData.append(imageData!,
                                         withName: "imagefile",
                                         fileName: "image.jpg",
                                         mimeType: "image/jpeg")
                for (key, value) in parameters {
                    multipartFormData.append(value.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
                }
        },
            to: completeUrl,
            headers: headers,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.responseJSON{ response in
                        print(response)
                    }
                case .failure(let encodingError):
                    print(encodingError)
                }
            }
        )

Postman Response Success on postman but having issue with headers, can you point out the silly mistake i have make


Solution

  • I believe you need to append the image this way

    multipartFormData.append(imageData!,
        withName: "profile_image",
        fileName: "image.jpg",
        mimeType: "image/jpeg")
    

    And you don't need to set or include parameters = ["profile_image": "image file"]

    As @rob mentioned, use Charles and compare the request from Postman with the request from the simulator. It will help to pinpoint what's different