swift - 使用Alamofire将图像上传到服务器

标签 swift image upload retrofit alamofire

出现了以下问题,事实是有时图像没有上传到服务器。所有数据都是正确的,图像存在,变量按正确顺序排列,函数报告上传成功,但有时图像仍然无法到达服务器。 Retorfit库不存在这样的问题,但Alamofire经常出现。我还不明白为什么。

class func write_photo(params:[String:String],image:UIImage, in_position:String, completion:_ js:String, _ success:Bool -> Void, failure:_ errorMessage:String,_ failure:Bool -> Void) {
    let url = BaseURL + "xdb_items.write_photo"
    let URL = try! URLRequest(url: url, method: .post)
    let in_idclient = params["in_idclient"]
    let in_iditem = params["in_iditem"]
    let imgData = UIImageJPEGRepresentation(image, 0.5)!
    sessionManagerImage.upload(multipartFormData: { multipartFormData in
        multipartFormData.append((in_idclient?.data(using: String.Encoding.utf8)!)!, withName: "in_idclient")
        multipartFormData.append((in_iditem?.data(using: String.Encoding.utf8)!)!, withName: "in_iditem")
        multipartFormData.append(imgData, withName: "in_filename", fileName: "photo", mimeType: "image/png")
        multipartFormData.append((in_position.data(using: String.Encoding.utf8)!), withName: "in_position")
    }, with: URL, encodingCompletion: {
        encodingResult in
        switch encodingResult {
            case .success(let upload, _, _):
            upload.response { response in
                completion("", true)
            }
            case .failure(let encodingError):
            print("ERROR RESPONSE: \(encodingError)")
        }
    })
}

我的 friend 们,当我进行应用程序部署时,Xcode 对 id_item 变量发出了这样的警告:无法执行支持代码来读取进程中的 Objective-C 类数据。在真实的 iPhone 设备上也许这就是问题

发现错误,状态代码 500,因为什么原因会发生?

postman 工作得很好! postman 截图: enter image description here enter image description here

Postman 提供的代码,但我需要 Alamofire:

    import Foundation

let headers = [
  "content-type": "multipart/form-data; boundary=----WeXXXXXXXXXXXXXXXXXXrZu0gW",
  "Authorization": "Basic dXXXXXXXXXXXX=",
  "cache-control": "no-cache",
  "Postman-Token": "2c1bXXXXXXXXXXXXXXXXX4e"
]
let parameters = [
  [
    "name": "in_filename",
    "fileName": "/home/iv/Рабочий стол/Скрины/Скрин6.png"
  ],
  [
    "name": "in_idclient",
    "value": "516"
  ],
  [
    "name": "in_iditem",
    "value": "1232"
  ],
  [
    "name": "in_position",
    "value": "5"
  ]
]

let boundary = "----WeXXXXXXXXXXXXXXXXXXrZu0gW"

var body = ""
var error: NSError? = nil
for param in parameters {
  let paramName = param["name"]!
  body += "--\(boundary)\r\n"
  body += "Content-Disposition:form-data; name=\"\(paramName)\""
  if let filename = param["fileName"] {
    let contentType = param["content-type"]!
    let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
    if (error != nil) {
      print(error)
    }
    body += "; filename=\"\(filename)\"\r\n"
    body += "Content-Type: \(contentType)\r\n\r\n"
    body += fileContent
  } else if let paramValue = param["value"] {
    body += "\r\n\r\n\(paramValue)"
  }
}

let request = NSMutableURLRequest(url: NSURL(string: "http://XXXXXXXXXX:XXXX/XX/xdb_items.write_photo")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()

最佳答案

尝试代替这个

multipartFormData.append(imgData, withName: "in_filename", fileName: "photo", mimeType: "image/png")

multipartFormData.append(imgData, withName: "profile_photo")

也许这对你有帮助

关于swift - 使用Alamofire将图像上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53778158/

相关文章:

ios - 如何使用附件复选标记取消选中 uitableview 单元格

ios - 切换 View Controller 后 NSTimer 触发两次

Python App Engine 上传图片内容类型

upload - InvalidPolicyDocument,缺少政策错误谷歌云存储

asp.net-mvc - <input type ="file"/> 的 Html 帮助器

xcode - PickerView 加载 tableview 数据 Swift

ios - Swift - 来自另一个类的运行方法

java - 在java中使用ESC/POS在热敏点打印机中打印位图整页宽度

ios - 图片IO : CreateMetadataFromXMPBufferInternal Threw error

javascript - 将鼠标悬停在 div 上时,多个图像取决于鼠标位置