如何使用Alamofire(帖子)上传图片?

时间:2019-03-29 12:21:22

标签: swift xcode upload alamofire

我必须提出一个API请求,以上传由相机拍摄还是从图库中拍摄的图像。已设置API中设置的方法,并且正文/参数中只有

key:file
value: // 

其中值是图片本身。 (在邮递员中,我只是从文件中上传图片即可使用),它返回带有其他信息的URL。 问题是我无法获得成功响应的请求,而且我不知道如何将UIImage传递给Alamofire。 这就是我所做的

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

我在控制台中遇到的错误如下:

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

我尝试使用随机图片网址,但是它也不起作用

4 个答案:

答案 0 :(得分:0)

使用Alamofire的上传方法在<?php $data=file_get_contents("https://gtfsr-pp.samtrafiken.se/otraf/TripUpdates.pb?key={API-key}"); echo $data->entity[0]->id; ?> 中上传图片。我已经为您更新了代码。使用以下代码。

multipartFormData

答案 1 :(得分:0)

 {
        let id : String = UserDefaults.standard.string(forKey: "id")!
        print(id)

        self.view.makeToastActivity(.center)

        Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(UIImageJPEGRepresentation(self.imageView.image!, 0.5)!, withName: "profile_pic", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
            for (key, value) in [“key”: "", ] {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }
        }, to:BaseURL + “base_url”)
        { (result) in
            switch result {
            case .success(let upload, _, _):

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

                upload.responseJSON { response in

                    if let JSON = response.result.value as? NSDictionary
                    {
                        print("JSON: \(JSON)")

                        let data = JSON["data"] as? NSArray


                        let status = JSON["status"] as? Int

                        if(status == 201)
                        {


                        }
                    }

                    self.view.hideToastActivity()
                }

            case .failure(let encodingError):
                //self.delegate?.showFailAlert()
                print(encodingError)
                self.view.hideToastActivity()
            }

        }
    }

答案 2 :(得分:0)

您可以使用多部分数据上传图像,请使用以下代码:

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

答案 3 :(得分:0)

我遇到了同样的问题,我已经通过以下方法解决了它: Alamofire 5.0.0-beta.5

AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "file",fileName: "file.jpg", mimeType: "image/jpg")
            },
        to: url).responseJSON
        { response in print(response)
            if let status = response.response?.statusCode {
                                print(status)
                            }
            //to get JSON return value
            if let result = response.value {
                let res = result as! [String: String]
                let newUrl:String = res["url"]!
                            print(newUrl)
            }
        }