我想使用Alamofire将多个图像上传到服务器。
一切正常,但只上传了一张图片。我需要上传多个图像或更多图像,具体取决于登录的用户。我正在使用一个名为DKImagePickerController
的库来从画廊或相机中挑选图像。
func upload() {
//shortcuts
let id = userr.integer(forKey: "id")
let plateId = plateIdTextField.text!
let customerName = customerNameTextField.text!
let customerContact = customerContactTextField.text!
let package = radioButtonsController.selectedIndex + 1
var parameters: [String: Any]
parameters = ["user_id": id,
"package": package,
"plate_id": plateId,
"customer_name": customerName,
"customer_contact": customerContact]
let spinningActivity = MBProgressHUD.showAdded(to: self.view, animated: true)
spinningActivity?.labelText = "uploading.."
spinningActivity?.detailsLabelText = "Please wait"
Alamofire.upload(multipartFormData: { multipartFormData in
for fileImage in self.fileUIImage {
multipartFormData.append(UIImagePNGRepresentation(fileImage)!, withName: "image", fileName:"image.png", mimeType: "image/png")
}
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
},
to: uploadURL,
method: HTTPMethod(rawValue: "POST")!,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
//Unpacking
guard let result = response.result.value else { return }
spinningActivity!.hide(true)
print("\(result)")
self.BackToHomePage()
}
case .failure(let encodingError):
print(encodingError)
}
})
}
有两种方法可以发送多个文件。
name
(在本例中,name
,image0
等的image1
值):
for (index, image) in images.enumerated() {
multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image\(index)", fileName: "image\(index).png", mimeType: "image/png")
}
这导致$_FILES
:
$_FILES = {
image0 = {
error = 0;
name = "image0.png";
size = 23578;
"tmp_name" = "/tmp/php1bc19G";
type = "image/png";
};
image1 = {
error = 0;
name = "image1.png";
size = 338685;
"tmp_name" = "/tmp/phpcGS5d6";
type = "image/png";
};
};
(忽略这个输出的格式,而只是关注这个嵌套目录结构中的键/值组合:就这个输出而言,我有web服务发送$_FILES
作为JSON,然后我让Alamofire解析它,并且这是在我的客户端应用程序中输出结果字典的方式。)name
来为[]
使用数组,例如字面上的image[]
:
for (index, image) in images.enumerated() {
multipartFormData.append(UIImagePNGRepresentation(image)!, withName: "image[]", fileName: "image\(index).png", mimeType: "image/png")
}
这导致在服务器上收到以下内容:
$_FILES = {
image = {
error = (
0,
0
);
name = (
"image0.png",
"image1.png"
);
size = (
23578,
338685
);
"tmp_name" = (
"/tmp/phpI4XrwU",
"/tmp/php3kVhhl"
);
type = (
"image/png",
"image/png"
);
};
};
它只取决于Web服务期望创建请求的方式。