我正在尝试使用Swift-SRWebClient http客户端框架将图像上传到Restful API。我使用以下方法上传图片。
var image:UIImage = UIImage(named: "apple.jpeg")
let imageData:NSData = NSData.dataWithData(UIImageJPEGRepresentation(image, 1.0))
SRWebClient.POST("http://www.tiikoni.com/tis/upload/upload.php")
.data(imageData, fieldName:"file", data:["days":"1","title":"Swift-SRWebClient","caption":"Uploaded via Swift-SRWebClient (https://github.com/sraj/Swift-SRWebClient)"])
.send({(response:AnyObject!, status:Int) -> Void in
//process success response
},failure:{(error:NSError!) -> Void in
//process failure response
})
此方法允许我仅上传单个图片。
请帮助我了解如何在一次POST中上传一系列图片或多张图片。
答案 0 :(得分:1)
感谢您的回复。我喜欢这个解决方案,修改this file并在其中添加以下更改。
/**
* Function to upload image & data using POST request
*
* @param image:NSData image data of type NSData
* @param fieldName:String field name for uploading image
* @param data:RequestData? optional value of type Dictionary<String,AnyObject>
*
* @return self instance to support function chaining
*/
public func data(image:[NSData], fieldName:String, data:RequestData?) -> SRWebClient {
let uniqueId = NSProcessInfo.processInfo().globallyUniqueString
var postBody:NSMutableData = NSMutableData()
var postData:String = String()
var boundary:String = "------WebKitFormBoundary\(uniqueId)"
self.urlRequest?.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField:"Content-Type")
if(data != nil && data!.count > 0) {
postData += "--\(boundary)\r\n"
for (key, value : AnyObject) in data! {
if let value = value as? String {
postData += "--\(boundary)\r\n"
postData += "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n"
postData += "\(value)\r\n"
}
}
}
for i in image{
postData += "--\(boundary)\r\n"
postData += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(Int64(NSDate().timeIntervalSince1970*1000)).jpg\"\r\n"
postData += "Content-Type: image/jpeg\r\n\r\n"
postBody.appendData(postData.dataUsingEncoding(NSUTF8StringEncoding)!)
postBody.appendData(i)
postData = String()
postData += "\r\n"
postData += "\r\n--\(boundary)--\r\n"
postBody.appendData(postData.dataUsingEncoding(NSUTF8StringEncoding)!)
}
self.urlRequest!.HTTPBody = NSData(data: postBody)
return self
}
现在我可以使用SRWebClient ...
添加多个图像