Search code examples
swiftxcodeuploadalamofire

How to upload pictures with Alamofire (post)?


I have to make an API request to upload an image which's whether been taken by the camera or picked from the gallery. The method set in the API is set and in the body/parameters there's only

key:file
value: // 

where the value is the picture itself. (in postman I just upload a picture from my files and it works) and it returns an URL with some other information. The issue is I can't get the request to have a successful response, and I don't know how I can pass the UIImage to Alamofire. This is what I have done

Alamofire.request(baseUrl,
          method: .post,
          parameters: ["file" : expenseImage])
.responseJSON(completionHandler: { response in
                            guard response.result.error == nil else {
                                print("Error subiendo la imagen \n\(response.result.error!)")
                                return
                            }

                            guard let json = response.result.value as? [String: Any] else {
                                if let error = response.result.error {
                                    print("Error: \(error.localizedDescription)")
                                }
                                return
                            }
                            do {
                                let decoder = JSONDecoder()
                                let rawData = try JSONSerialization.data(withJSONObject: json, options: [])
                                let dataObject = try decoder.decode(PutObjectFile.self, from: rawData)
                                finished(dataObject)
                                print(dataObject)

                                print(dataObject.msg.file_info.url)
                            } catch let error {
                                print("Error decoding:\n\(error)")
                            }
                          })

and the error I'm getting in the console is the following:

responseSerializationFailed(reason: Alamofire.AFError
.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

I tried using a random picture url but it doesn't work either


Solution

  • You can upload images using multipart data, Use below code:

    let manager = Alamofire.SessionManager.default
        do{
            manager.upload(multipartFormData: { (formData) in
                if let fileData = fileData { // File data
                    formData.append(fileData, withName: "FILE_NAME", fileName: "simple.jpeg", mimeType: "image/jpeg")
                }
            }, to: "API_PATH", method: HTTPMethod.post, headers: nil, encodingCompletion: { encoding in
                switch encoding{
                case .success(let req, _, _):
                    req.uploadProgress(closure: { (prog) in
                        progress?(prog)
                    }).responseJSON { (resObj) in
                        switch resObj.result{
                        case .success:
                            if let resData = resObj.data{
                                do {
                                    let res = try JSONSerialization.jsonObject(with: resData)
                                    print(res) // Success
                                } catch let err{
                                    print(err)
                                }
                            }
                            break
                        case .failure(let err):
                            print(err)
                            break
                        }
                    }
                    break
                case .failure(let err):
                    print(err)
                    break
                }
            })
        }catch let err{
            print(err)
        }