Search code examples
iosswiftalamofire

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

            print(response)
            print(response.result)
            print(response.request)
            print(response.response)

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

However I received this message

JSON: {
  "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!


Solution

  • 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)")
            }
    })