如何使用Alamofire上传图像和引用的文件中PARAMS
问题描述:
我可以发送图像的API(节制),像这样它在邮递员链接到一个“媒体” PARAM:如何使用Alamofire上传图像和引用的文件中PARAMS
现在我正在试图迅速做同样的事情。我遵循示例here但出现错误:未指定媒体。继承人我的代码:附加的图像文件没有正确链接到媒体参数?
let image = self.descriptionImage.image!
let parameters = [
"api_user": "xxxxx",
"api_secret": "xxxxx",
"models": "nudity,wad",
"media": "file.png"
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 1) {
multipartFormData.append(imageData, withName: "file.png", fileName: "file.png", mimeType: "image/png")
}
for p in parameters {
let value = p.value
multipartFormData.append((value.data(using: .utf8))!, withName: p.key)
}}, to: "https://api.sightengine.com/1.0/check.json", method: .post, headers: nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
print(response.data)
print("strongSelf")
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
答
对图像的参数应该在多形式的数据来指定,尝试更改代码下面:
let image = self.descriptionImage.image!
let parameters = [
"api_user": "xxxxx",
"api_secret": "xxxxx",
"models": "nudity,wad"
]
Alamofire.upload(multipartFormData: { multipartFormData in
if let imageData = UIImagePNGRepresentation(image) {
multipartFormData.append(imageData, withName: "media", fileName: "file.png", mimeType: "image/png")
}
for p in parameters {
let value = p.value
multipartFormData.append((value.data(using: .utf8))!, withName: p.key)
}}, to: "https://api.sightengine.com/1.0/check.json", method: .post, headers: nil,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.response { [weak self] response in
guard let strongSelf = self else {
return
}
print(response.data)
print("strongSelf")
debugPrint(response)
}
case .failure(let encodingError):
print("error:\(encodingError)")
}
})
OMG感谢你这么多,我已经与彻夜狂欢一直在挣扎:DDD – user3517546
@ user3517546很高兴它可以帮助你。 – chengsam