我正在尝试快速上传多张图像。请看下面的代码。我只上传第一张图片,其余的都不上传。
dic:[String:Any]
的位置-成功上载的一些字符串值。
还有imageData:[Data]
:-包含jpg图像数据数组
private class func loadServerURL(url: URL, dic:[String:Any], imageData:[Data] , completion:@escaping(_ success:Bool, _ data:[String:Any]?, _ error:Error?)->Void){
let accessToken = CurrentSession.instance.access_token
// let request = NSMutableURLRequest(url:url as URL)
var request = URLRequest(url: url)
request.httpMethod = "POST";
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
let boundary = "0xKhTmLbOuNdArY"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var uploadData = Data()
for (index,dta) in imageData.enumerated(){
print("Loop Index : \(index)")
let img = createBodyWithParameters(parameters: dic, filePathKey: "UploadedImage_\(index)", imageDataKey: dta as NSData, boundary: boundary, imgName: "\(index)") as Data
uploadData.append(img)
}
request.httpBody = uploadData
let loadDataTask = URLSession.shared.dataTask(with: request) { (data, resposne, error) in
if let _ = error{
completion(false,nil,error)
}
else if let response = resposne as? HTTPURLResponse{
if response.statusCode != 200{
if error == nil{
}
completion(false,nil,error)
}
else{
do {
if let parsedData = try? JSONSerialization.jsonObject(with: data!) {
let ff = parsedData as? Dictionary<String,Any>
print(ff?["status"] ?? "fdf")
// If session expires logout from the application
if let _ = ff!["Message"] as? String{
if (ff!["Message"] as! String == "Authorization has been denied for this request.") {
}
}
completion(true,parsedData as? Dictionary<String, Any>,nil)
}
}
}
}
}
loadDataTask.resume()
}
private class func createBodyWithParameters(parameters: [String: Any]?, filePathKey: String?, imageDataKey: NSData, boundary: String,imgName:String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
// let filename = String.getTodayString() + "\(imgName).jpg"
let filename = "profile_\(imgName).jpg"
print("image_NAME--- \(filename)")
// let filename = "img.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey as Data)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}