简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM