【问题标题】:Swift 3 How To Send A Multipart Post Request With VaporSwift 3 如何使用 Vapor 发送多部分发布请求
【发布时间】:2016-11-21 20:32:16
【问题描述】:

我正在使用 vapor 来为我的应用托管图像。我有以下代码来接收图像并打印它。

drop.post("saveArt") { request in
if let contentType = request.headers["Content-Type"], contentType.contains("image/png"), let bytes = request.body.bytes {
    let image = NSImage(data: Data(bytes))
    print(image)
    return JSON(["Testawesome":"awesome123"])
}
return JSON(["test":"123"])
}

如何仅使用 swift 发送多部分请求?这是我正在使用的当前发布请求代码。

 let tiffData = imagetosend?.tiffRepresentation
 let imageRep = NSBitmapImageRep(data: tiffData!)
 let image_data = imageRep?.representation(using: .JPEG, properties: [:])
 print("Hi")

 let url = NSURL(string: "http://localhost:8080/getArt")

let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"


//define the multipart request type

request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")


let body = NSMutableData()

let mimetype = "image/png"

//define the data post parameter




body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)


request.httpBody = body as Data



let session = URLSession.shared


let task = session.dataTask(with: request as URLRequest) {
    (
    data, response, error) in

    guard let _:NSData = data as NSData?, let _:URLResponse = response  , error == nil else {
        print(error?.localizedDescription)
        return
    }

    let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
    print(dataString)

}

task.resume()

【问题讨论】:

  • 您想从 Vapor、OSX 或 iOS 应用程序发送这些数据?
  • 您可以像在这个答案中一样使用 Alamofire stackoverflow.com/a/32204889/3803872
  • 答案没有帮助我会发布对我有用的。

标签: swift xcode post vapor


【解决方案1】:

我用这个 alamofire 方法解决了它。

Alamofire.request("YOUR URL", method: .post, parameters: parm, encoding: JSONEncoding.default).responseJSON(completionHandler: { json in
        // If you want to return json.
        print(json)
    })

【讨论】:

  • 想知道您是如何使用 Alamofire 在 Linux 机器上放置代码的。我将 Alamofire 版本 4 添加到我的 Vapor 项目中,但由于 NetworkReachabilityManager.swift 中缺少模块 SystemConfiguration,因此无法在 Vapor.cloud 上构建项目。 (代码当然在我的 Mac 上运行)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 2018-03-19
  • 2016-05-22
  • 2011-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多