我目前正在尝试使用预先签名的网址将图像上传到亚马逊。
它的工作方式是,我发出 GET 请求来获取预签名的 URL,然后发出 PUT 请求以使用 GET 请求返回的 url 上传图像。
这两条规则是:Content-Type 必须是 image\jpeg,http 方法必须是 PUT。
因此,目前我的上传代码返回 200,但亚马逊拒绝该数据。
这是我的代码:
上传返回的实际url是:
var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["Content-Type"] = "image/jpeg"
let URL = try! URLRequest(url: url, method: .put, headers: headers)
Alamofire.upload(multipartFormData: { (multipartFormData) in
let compressionQuality: CGFloat = 0.8
guard let imageData = UIImageJPEGRepresentation(image, compressionQuality) else {
print("Unable to get JPEG representation for image \(image)")
return
}
multipartFormData.append(imageData, withName: "image.jpg", mimeType: "image/jpeg")
// code
}, with: URL, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.responseJSON { response in
print("SUCCESS -> \(response.request?.allHTTPHeaderFields)")
}
case .failure(let encodingError):
print(encodingError)
}
})
我怀疑当我打印 http 标头时,Content-Type 总是显示 multipart/form-data 而不是我需要的 image/jpeg,但目前我不知道如何解决这个问题。
实际上我最近也有同样的要求(除了我需要 PNG 而不是 JPG)。
以下是您的做法。
let compressionQuality: CGFloat = 0.8
guard let imageData = UIImageJPEGRepresentation(image, compressionQuality) else {
print("Unable to get JPEG representation for image \(image)")
return
}
let headers = [
"Content-Type": "image/jpeg"
]
// presignedUrl is a String
Alamofire.upload(imageData, to: presignedUrl, method: .put, headers: headers)
.responseData {
response in
guard let httpResponse = response.response else {
print("Something went wrong uploading")
return
}
if let publicUrl = presignedUrl.components(separatedBy: "?").first {
print(publicUrl)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)