【问题标题】:How to send an image via a POST request in Swift 4?如何通过 Swift 4 中的 POST 请求发送图像?
【发布时间】:2018-07-18 12:27:12
【问题描述】:
func createPost(username: String, user_id: String, description: String, image: UIImage, completion: @escaping (Bool) -> ()) {
    var request = URLRequest(url: URL(string: Globals.root+"/amazing/image/post/here")!)
    request.httpMethod = "POST"
    //request.httpBody = .data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }
        if let data = data {
            do {
                let aaData = try JSONSerialization.jsonObject(with: data, options: [])
                if let ppData = aaData as? [String:Any] {
                    let u = ppData["username"] as! Bool
                    if u == true {
                        completion(true)
                    }
                }
            } catch let error as NSError {
                print(error.localizedDescription)
                completion(false)
            }
        }
    }
    task.resume()
}

我一直在寻找一个有效的答案,但我没有找到任何与 Swift 4 相关的答案。我希望能够将图像发送到我的 RESTful API 而不对其进行编码。怎么可能做到这一点?提前致谢。 :)

【问题讨论】:

  • 使用多部分形式发送图像和其他参数。对于多部分使用,可以使用 Alamofire。

标签: ios swift https swift4 flask-restful


【解决方案1】:

首先,考虑到您要发送用户名和图像,它必须是多部分形式(或一些丑陋的 BASE64 编码 JSON 属性)。

通常来说,干净的方法是首先通过二进制正文发布上传图片(因为图片是唯一传输的东西,而且速度也更快),获取 Id 并将其作为字段引用。

做不到这一点,还是挺难的,用Moya + AlamoFire怎么样?

https://github.com/Moya/Moya/issues/598

图像是二进制对象,这不是有效的 HTTP,除非您通过多部分形式对其进行编码或将其包装为 JSON 安全 Base-64(假设您使用的是 JSON)

【讨论】:

  • 虽然这是一个不错的主意,但在大容量时它可能会搞砸,因为您会找到刚刚发布的图像的 id。就个人而言,我宁愿一次性发送所有内容(图像和元数据)。我曾考虑过使用 AlamoFire,但我反对。
  • 您只有在发布后才能获得 ID,您先启动它。如果必须的话,使用多部分表单和 AlamoFire,你控制后端吗?
  • 我写了后端。我使用 Python + Flask。
  • 我建议你要么做多部分表单或图像上传+请求发送。就个人而言,我会选择异步上传图片,获取媒体 ID 并附加成功,但这是您的选择,请记住多部分表单可能会变得混乱,Flask 会对此进行一些抽象。
  • 我决定使用 Alamofire。你知道如何使用它吗?
猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 2018-04-20
  • 2021-08-02
  • 2019-11-24
  • 2020-05-12
  • 2021-11-18
  • 1970-01-01
  • 2015-07-24
相关资源
最近更新 更多