Rameswar Prasad
Rameswar Prasad

Reputation: 1331

Multipart form data upload with Alamofire shows file missing in server

I'm trying to upload an image using Alamofire, the response shows success but the picture doesn't get uploaded. When I debugged with backend developer, it seemed the file attachment is missing in the request. However, the progress shows uploading details of the file. Can anyone help what's going wrong here.

class ImageUploadClient {
        class func upload(image: UIImage, to request: URLRequest) {
            let imgData = UIImageJPEGRepresentation(image, 0.5)!
            let filename = "file.jpeg"        

            Alamofire.upload(multipartFormData: { (multiPartData) in
                multiPartData.append(imgData, withName: filename, mimeType: "image/jpg")
            }, usingThreshold: UInt64(1024),
               with: request, encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let request, let streamingFromDisk, let fileURL):
                    debugPrint(streamingFromDisk)   // Shows true
                    debugPrint(fileURL)             // Returns file url
                    debugPrint(request)

                    // upload progress closure
                    request.uploadProgress(closure: { (progress) in
                        print("upload progress: \(progress.fractionCompleted)")
                        // here you can send out to a delegate or via notifications the upload progress to interested parties
                    })

                    // response handler
                    request.validate()
                        .responseJSON(completionHandler: { (response) in
                            switch response.result {
                            case .success(let value):
                                debugPrint(value)

                            case .failure(let err):
                                debugPrint(err)
                            }
                        })

                // encodingResult failure
                case .failure(let error):
                    debugPrint(error)
                }
            })
        }
    }

Upvotes: 0

Views: 739

Answers (1)

Neel Bhasin
Neel Bhasin

Reputation: 759

try by adding file name for your image

like this

and withName key will contain Key name to your image on server

let profileKey = "profileImage"

multiPartData.append(imgData, withName: profileKey, fileName: filename, mimeType: "image/jpg")

Upvotes: 1

Related Questions