我正在使用以下代码将图像上传到服务器,它工作正常,但我需要根据一个参数(即“hunter_pictures”)上传一组或图像列表
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(UIImageJPEGRepresentation(spottingImage, 1)! , withName: "hunt_pictures", fileName: "user.jpg", mimeType: "image/jpeg")
multipartFormData.append((userID.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "user_id")
},
to: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
case .failure(let encodingError):
print(encodingError)
}
})
@maxwel 的答案只做了一项修改,只需在文件名“hunter_picture.jpg”中添加文件格式。添加了 .jpg 并且它起作用了
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append((userId.data(using: String.Encoding.utf8, allowLossyConversion: false))!, withName: "userID")
for (index,image) in self.spottingImages.enumerated() {
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "hunter_picture[\(index)]", fileName: "hunter_picture.jpg", mimeType: "image/jpeg") }
}
},
to: url,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
print(upload)
case .failure(let encodingError):
print(encodingError)}
})
试试这个方法:
func uploadImages(pictures: [UIImage]) {
let url = "your url"
let headers: HTTPHeaders = [Keys.authorization: "your token"]
Alamofire.upload(multipartFormData: { multipartFormData in
for image in pictures {
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "pictures[\(index)]", fileName: "picture", mimeType: "image/jpeg")
}
}
}, to: url, method: .post, headers: headers) { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
let json = response.result.value
print(json)
}
case .failure(let encodingError):
print(encodingError.localizedDescription)
}
}
}
整合多图上传步骤:
将图像数组和参数作为函数参数发送,并带有成功和失败闭包。
将图像和参数附加到
multipartFormData
在相应的闭包中返回
success
/ failure
。代码片段:
func callAPIForImagesUpload(images: [UIImage],
parameters:[String: String]?,
success:@escaping ((_ response: Any?) -> Void),
failure:@escaping ((_ error: Error?) -> Void)) {
let apiURL = "xyz/"
let requestHeaders: HTTPHeaders = ["Authorization": "token value"]
let fileName = "user" // This will be the parameter name in which server is expecting the image data
Alamofire.upload(multipartFormData: { multipartFormData in
for i in 0..<images.count {
if let imageData = UIImageJPEGRepresentation(images[i], 1) {
multipartFormData.append(imageData, withName: "image_" + "\(i)", fileName: fileName, mimeType: "image/jpeg")
}
}
// Append parametrs too, if any
let params = parameters ?? [String: String]()
for (key, value) in params {
// Appending parameters in the request
multipartFormData.append((value.data(using: .utf8))!, withName: key)
}
}, to: apiURL, method: .post, headers: requestHeaders) { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
// Check whether status code lie between `200-300` range; mostly it would be `200`
upload.validate(statusCode: 200..<300).responseJSON(completionHandler: { receivedInfo in
print("Success: \(receivedInfo.result.value ?? "error occurred in response value")")
success(receivedInfo.result.value)
})
case .failure(let error):
print("Error: \(error.localizedDescription)")
failure(error)
}
}
}