上传图片使用Alamofire服务器

问题描述 投票:0回答:2

下面的问题出现了,但事实是,有时图像不会上传到服务器。所有的数据是正确的,图像存在,变量被安排在正确的顺序,功能报告上传成功,但有时图像仍然没有到达服务器。有没有这样的问题,与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)")
        }
    })
}

我的朋友,当我做应用部署,在Xcode中发布了关于id_item变量这样的警告:不能执行支持代码的过程中阅读Objective-C类的数据。在真正的iPhone设备,也许这就是问题所在

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

邮差的工作太棒了!截图邮差:enter image description here enter image description here

代码邮差提供,但我需要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()
swift image upload retrofit alamofire
2个回答
0
投票

试试这个代替

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

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

可能是你这会有所帮助


0
投票
let imageData : Data! = (UIImage converted to Data) 

Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append(imageData, withName: "image", fileName: "file.jpeg", mimeType: "image/jpeg")
            }, to: NSURL(string: "http://URL you want to upload it to")! as URL)
            { (result) in
                switch result {
                case .success(let upload, _, _):
                   //Success
                case .failure(let encodingError):
                    //Failure
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.