2016-11-21 73 views
0

我正在使用蒸氣託管我的應用程序的圖像。我有以下代碼來接收圖像並打印它。Swift 3如何發送與蒸氣多部分發布請求

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() 
+0

你想從Vapor,OSX或iOS應用程序發送此數據? – Quver

+0

你可以在這個答案中使用Alamofire http://stackoverflow.com/a/32204889/3803872 – Quver

+0

答案沒有幫助我會發佈一個爲我工作的。 –

回答

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) 
    }) 
+0

知道如何在Linux機器上使用Alamofire編寫代碼會很有趣。我將Alamofire第4版添加到了我的Vapor項目中,但由於NetworkReachabilityManager.swift中缺少模塊SystemConfiguration,無法在Vapor.cloud上構建項目。 (當然,代碼在我的Mac上工作) – Gabriel