我有参数数组和图像数组,每组参数包含一个且只有一个图像。我的代码
let imgData = UIImageJPEGRepresentation(imageView.image!, 0.2)!
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
},
to:URLUpdateProfile,
method:.post,
headers:headers)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
}
}
使用这段代码我可以上传一张图片和一个参数。但是我想发送数组中的参数和数组中的图像。上传参数数组和图像数组的方法是什么?如果是,如何跟踪图像和参数?
最佳答案
您可以在 Operation
中上传每张图片及其参数。您的 Operation
应如下所示:
class UploadImageOperation: Operation {
private var image: UIImage
init(withImage: UIImage) {
super.init()
image = withImage
}
override func main() {
let imgData = UIImageJPEGRepresentation(image, 0.2)!
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in params {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
},
to:URLUpdateProfile,
method:.post,
headers:headers)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
})
upload.responseJSON { response in
print(response.result.value)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
}
然后创建操作并将它们添加到队列中,如下所示:
let opQueue = OperationQueue()
opQueue.name = "imageUploadQueue"
opQueue.maxConcurrentOperationCount = 5 //number of images you want to be uploaded simultaneously
opQueue.qualityOfService = .background
for image in arrayOfImages {
let uploadImageOperation = UploadImageOperation(withImage: image)
opQueue.addOperation(uploadImageOperation)
}
关于ios - 使用 Alamofire 使用参数数组上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43972651/