【问题标题】:how to upload image using alamofire and parameters in array form如何使用 alamofire 和数组形式的参数上传图像
【发布时间】:2020-08-05 09:15:42
【问题描述】:

我尝试了很多解决方案,但在使用 alomafire 将图像上传到服务器时总是出现此错误

尾随闭包传递给不接受闭包的“FileManager”类型参数

 let params: Parameters = ["name": "abcd","gender": "Male", "hobbies" : HobbyArray]
  AF.upload(multipartFormData:
      {
          (multipartFormData) in
          multipartFormData.append(UIImageJPEGRepresentation(self.yourimageView.image!, 0.1)!, withName: "image", fileName: "file.jpeg", mimeType: "image/jpeg")
          for (key, value) in params
          {
              multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
          }
  }, to: "\(BaseUrl)/save-beers" , headers:nil)
  { (result) in
      switch result {
      case .success(let upload,_,_ ):
          upload.uploadProgress(closure: { (progress) in
              //Print progress
          })
          upload.responseJSON
              { response in
                  //print response.result
                  if response.result.value != nil
                  {
                      let dict :NSDictionary = response.result.value! as! NSDictionary
                      let status = dict.value(forKey: "status")as! String
                      if status=="1"
                      {
                        print("DATA UPLOAD SUCCESSFULLY")
                      }
                  }
          }
      case .failure(let encodingError):
          break
      }
  }
    

【问题讨论】:

  • @VedSharma 这个答案对我没用,已经尝试过这种类型的答案
  • 您使用的是哪个版本的 alamofire?
  • @ReinierMelian Alamofire 5.0.0

标签: ios swift iphone xcode alamofireimage


【解决方案1】:

您可以使用此代码上传图片

//MARK: - Upload image using alamofire with multiparts
func uploadImageAPIResponse(postPath:String,img: UIImage, parameters:NSDictionary, requestType: RequestType){
    let imgData = img.jpegData(compressionQuality: 0.5)!
    let headers: HTTPHeaders = ["Authorization": "Your_Auth if any otherwise remove Header from request"]
    print("postPath:\(postPath)\nheaders:\(headers)\nparameters: \(parameters)")
    
    Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "file",fileName: "profile.jpg", mimeType: "image/jpg")
            for (key, value) in parameters {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key as! String)
                } //Optional for extra parameters
        },
    to:postPath)
    { (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 as Any)
                
                if  response.result.isSuccess
                {   let httpStatusCode: Int = (response.response?.statusCode)!
                    let data = (response.result.value as? NSDictionary)!
                    let meta = (data["meta"] as? NSDictionary)!
                    let code = meta["code"] as? Int ?? 0
                    print(data)
                    //if (data["success"] as? Bool)! {
                    print("httpCode" + String(httpStatusCode))
                    print("code" + String(code))
                    switch(httpStatusCode) {
                    case 200://operation successfull
                        if code == 401 {
                            let deleg = UIApplication.shared.delegate as! AppDelegate
                            User.defaultUser.logoutUser()
                            deleg.showLoginScreen()
                        }
                        self.delegate?.requestFinished(responseData: data, requestType: requestType)
                        break
                    case 204://no data/content found
                        self.delegate?.requestFinished(responseData: data, requestType: requestType)
                        break
                    case 401://Request from unauthorized resource
                        
                        self.delegate?.requestFailed(error: "Request from unauthorized resource", requestType: requestType)
                        break
                    case 500://Internal server error like query execution failed or server script crashed due to some reason.
                        self.delegate?.requestFailed(error: "Internal server error like query execution failed or server script crashed due to some reason.", requestType: requestType)
                        break
                    default:
                        self.delegate?.requestFinished(responseData: data, requestType: requestType)
                        break
                    }
                }
                else
                {
                    self.delegate?.requestFailed(error: (response.result.error?.localizedDescription)!, requestType: requestType)
                }
                
            }

        case .failure(let encodingError):
            print(encodingError)
            self.delegate?.requestFailed(error: encodingError.localizedDescription, requestType: requestType)
        }
    }
    
}

【讨论】:

    猜你喜欢
    • 2018-02-14
    • 1970-01-01
    • 2023-03-22
    • 2014-12-17
    • 2017-07-14
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多