gpt4 book ai didi

ios - 如何使用 Alamofire 5 将图像作为多部分数据上传到 aws 预签名 url?

转载 作者:行者123 更新时间:2023-11-29 05:08:18 39 4
gpt4 key购买 nike

我正在尝试将图像上传到预签名的 AWS URL。我尝试使用接受 multipartData 的 Alamofire 5 上传方法。我在使用 Alamofire 5 分段上传时收到 403 错误。

当我尝试使用 URLSession 时,它工作正常。

/// Working code

var request: URLRequest = URLRequest(url: requestURL)
request.httpMethod = "PUT"
request.httpBody = image
request.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
let tasksession: URLSessionDataTask = session.dataTask(with: request, completionHandler: { (response, urlResp, error) in
if let data: Data = response {
do {
let json: [String: Any]? = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
debugPrint("json \(json)")
}
catch {
debugPrint("error \(error)")
}
}



print(response ?? "response nil")
print(error ?? "response nil")
})
tasksession.resume()

同样,当我尝试使用 AF 5 时,它不起作用

//无效代码。

 AF.upload(multipartFormData: { (multiPart) in

multiPart.append(imageData, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
}, to: url, method: .put, headers: ["Content-Type": "image/jpeg"],
])
.uploadProgress(queue: .main, closure: { progress in
//Current upload progress of the file
print("Upload Progress: \(progress.fractionCompleted)")
})
.responseJSON(completionHandler: { data in
let json: [String: Any]? = data as? [String: Any]
debugPrint("upload complete json \(data)")
})

有人可以告诉为什么它不能使用 Alamofire 5 进行分段上传吗?分段上传可以在 Android 中使用。

最佳答案

Alamofire 版本 4.9.1

Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
//Any Post Params if you have.
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to:uploadUrlStr) //uploadUrlStr: upload url in your case
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Uploading")
print(CGFloat(progress.fractionCompleted * 100))
})

upload.responseJSON { response in
print("Upload Finished")
guard let resultValue = response.result.value else {
NSLog("Result value in response is nil")
return
}

}

case .failure(let encodingError):
print(encodingError.localizedDescription)
}
}

这对我有用。

关于ios - 如何使用 Alamofire 5 将图像作为多部分数据上传到 aws 预签名 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59948262/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com