Kevin Sabbe Kevin Sabbe - 1 year ago 84
iOS Question

Swift 3 Upload Image Issue (format)

I have to upload image to backend (PHP) and I have to send it with parameter name : "picture"

func uploadImage(token: String, userID: Int, imgStr: String,
successBlock: @escaping (JSON, Int) -> (),
failureBlock: @escaping (String) -> ())
let params: [String: Any] = [
"picture" : imgStr

Alamofire.request( "\(API_URL)" + "users/\(userID)",
method: .put,
parameters: params,
encoding: JSONEncoding.default,
headers: Headers().withToken(token: token)).responseJSON
{ response in


response.result.error != nil
? (failureBlock(response.result.error!.localizedDescription))
: (successBlock(JSON(response.result.value),

However I received this message

"picture" : [
"The picture must be a file of type: jpeg, jpg, png."

There are way to convert UIImage to String with png/jpeg format ?

Many thanks!

Answer Source

This is how you can send image to server with file format

let headers: HTTPHeaders = [String:String]
let URL = try! URLRequest(url: yourURL, method: .put, headers: headers)

Alamofire.upload(multipartFormData: { multipartFormData in
    if let _image = UIImage(named:"") {
        if let imageData = UIImagePNGRepresentation(_image) {
            multipartFormData.append(imageData, withName: "signImg", fileName: "picture.png", mimeType: "image/png")
    }, with: URL, encodingCompletion: {
        encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint("SUCCESS RESPONSE: \(response)")
        case .failure(let encodingError):
            // hide progressbas here
            print("ERROR RESPONSE: \(encodingError)")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download