我用下面的代碼到一個單一的圖像上傳到服務器:上傳在迅速多幅圖像使用Alamofire
private static func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData?, imageName: String) -> (URLRequestConvertible , NSData) {
// create url request to send
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
let boundaryConstant = "myRandomBoundary12345";
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
if(imageData != nil && imageData?.length != 0) {
// add image
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"\(imageName)\"; filename=\"\(StringHelper.sharedInstance.randomString(5)).png\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData(imageData!)
}
// add parameters
for (key, value) in parameters {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
print("upload",parameters)
// return URLRequestConvertible and NSData
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}
我如何可以通過修改這些代碼上傳單個參數多張圖片?
如何上傳多張圖片陣列在一個單一的pararmeter –
你可以讓一個struct是把你的所有FUNC參數,可以再創建一個函數,這些結構的數組,然後在功能,您可以遍歷該數組,然後返回一個請求數組。如果您希望全部一次完成,因爲在完成所有上傳時需要執行某些操作,請查看操作隊列或調度組 – JustinM
請參閱鏈接http://stackoverflow.com/questions/28448837/uploading-multiple-圖像文件與迅速,http://stackoverflow.com/questions/40527140/mysql-and-swift-upload-image-and-file-would-it-be-better-to-use-alamofire –