Search code examples
swiftalamofire

Alamofire photo upload with key of the file in body


I am able to upload a photo via Postman but in my iOS application it fails, and it is so weird that I still get a .success from encodingCompletion.

Here is part of my code

UpdateUserInfo

    //
    // Update user info
    //
    func updateUserInfo(){
        var imageData: Data!
        var url = ""
        if let userId = KeychainWrapper.standard.string(forKey: USER_ID_KEY){
            url = URL_USER_UPLOAD_PIC + userId
        }
        if pickedImage != nil{
            imageData = UIImagePNGRepresentation(pickedImage)
            //imageData = UIImageJPEGRepresentation(pickedImage!, 1.0)
        }
        let token = KeychainWrapper.standard.string(forKey: USER_LOGIN_TOKEN_KEY)!


        let headers: HTTPHeaders = [
            "Authorization": "Bearer \(token)"
        ]

        if imageData != nil{
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(imageData!, withName: "fileset", fileName: "file.png", mimeType: "image/png")
            }, to: url,
               method: .post,
               headers: headers,
               encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    print("Donkey Success \(String(describing: upload.response?.statusCode))")
                    upload.responseString(completionHandler: { (response) in
                        debugPrint(response)
                    })
                case .failure(let encodingError):
                    print(encodingError)
                    print("Donkey Fail")
                }
            })
        }


    }

and in my postman I have

Postman

enter image description here

My first question is why I am getting a .success if it fails to upload?

and my second question is, do I need to put the key "pic" (seen in Postman) somewhere in my request? if so where?

Thanks for any help in advance


Solution

  • In Post man Image Key is pic but in your code its "fileset"

    change to

            multipartFormData.append(imageData!, withName: "pic", fileName: "file.png", mimeType: "image/png")
    

    And success is Result of encoding not uploading processs

    EncodingResult is MultipartFormDataEncodingResult that Defines whether the MultipartFormData encoding was successful and contains result of the encoding as associated values. - Success: Represents a successful MultipartFormData encoding and contains the new UploadRequest along with streaming information. - Failure: Used to represent a failure in the MultipartFormData encoding and also contains the encoding