简体   繁体   English

Swift 3如何通过蒸气发送多部分后请求

[英]Swift 3 How To Send A Multipart Post Request With Vapor

I'm using vapor to host images for my app.I have the following code to recieve the image and print it. 我正在使用蒸气为我的应用程序托管图像。我有以下代码来接收图像并打印。

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"])
}

How can I send a multipart request using just swift?.Here is the current post request code i'm using. 如何仅使用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()

I solved it using this alamofire method. 我使用这种alamofire方法解决了它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM