Anoop Krishnan
Anoop Krishnan

Reputation: 331

How to upload UIImage with some key and values to server with Alamofire

I am using alamofire to upload an image along with some parameters to server, how ever I am getting ambitious reference to member upload error..

What could be the issue? My code is.

public var selectedImage: UIImage?
...
let parameters: Parameters = ["user_id":  "1","description": "test"];
    Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(selectedImage, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
        } //Optional for extra parameters
    }, to:"mysite/upload.php")
        .uploadProgress { progress in // main queue by default
            print("Upload Progress: \(progress.fractionCompleted)")
        }
        .downloadProgress { progress in // main queue by default
            print("Download Progress: \(progress.fractionCompleted)")
        }
        .responseJSON { response in
            debugPrint(response)
    }

Upvotes: 0

Views: 309

Answers (2)

Dixit Akabari
Dixit Akabari

Reputation: 2547

Try this its working fine for me.

    let selectedImage: UIImage?

    let parameters: Parameters = ["user_id":  "1","description": "test"];

    Alamofire.upload(multipartFormData: { MultipartFormData in

        for (key, value) in parameters {
            MultipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

        let imgData = UIImageJPEGRepresentation(selectedImage!,1)
        MultipartFormData.append(imgData!, withName: "fileset", fileName: "file.jpeg", mimeType: "image/jpeg")

    }, to: "mysite/upload.php") { (result) in
        switch result {
        case .success(let upload, _, _):

        upload.uploadProgress(closure: { (Progress) in
              print("Upload Progress: \(Progress.fractionCompleted)")
           })

            upload.responseJSON { response in
                print(response.result.value!)
            }

        case .failure(let encodingError):
            print(encodingError.localizedDescription)
            break
        }

    }

Upvotes: 1

mojtaba al moussawi
mojtaba al moussawi

Reputation: 1398

You are uploading the UIImage itself! which is incorrect.

instead you must convert it to a data before uploading it...

So before this line of code

multipartFormData.append(selectedImage, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")

try to get the data from the selected image:

var imageData : Data?
    if let image = selectedImage{
        imageData = UIImageJPEGRepresentation(image , 0.7)!
    }

Then you can upload it:

if let data = imageData{

            multipartFormData.append(data,"fileset",fileName: "file.jpg", mimeType: "image/jpg")
        }

Upvotes: 0

Related Questions