如何使用 alamofire 和数组形式的参数上传图像

Posted

技术标签:

【中文标题】如何使用 alamofire 和数组形式的参数上传图像【英文标题】:how to upload image using alamofire and parameters in array form 【发布时间】: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
      
  
    

【问题讨论】:

试试这个答案:***.com/questions/62976628/… @VedSharma 这个答案对我没用,已经尝试过这种类型的答案 您使用的是哪个版本的 alamofire? @ReinierMelian Alamofire 5.0.0 【参考方案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)
        
    
    

【讨论】:

以上是关于如何使用 alamofire 和数组形式的参数上传图像的主要内容,如果未能解决你的问题,请参考以下文章

Swift Alamofire 发送图像数组和其他参数

如何使用 multipartFormData 和参数上传图像,使用 Alamofire 4.3 请求所需的身份验证

如何在 Swift 中使用 Alamofire 上传带有 JSON 参数的图像?

如何在 Swift 4 中使用 Alamofire 上传具有其他参数的多个图像

如何使用新的 Swift 3 和 Alamofire 解析 JSON(字典和数组)

Alamofire,使用参数中的结构上传 MultipartFormData