我尝试通过 AWSS3 SDK swift 将文件上传到 S3 服务。 我的代码:
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: Config.main.accessKey, secretKey: Config.main.secretKey)
let configuration = AWSServiceConfiguration(region: .USEast1, endpoint: AWSEndpoint(url: URL(string: Config.main.AWS_ENDPOINT)!), credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let image = UIImage(named: "photo")!
let data: Data = image.pngData()!
let remoteName = generateRandomStringWithLength(length: 12) + "." + data.format
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent(remoteName)
try! data.write(to: fileURL, options: .atomic)
upload(fileUrl: fileURL, fileData: data, fileName: remoteName, type: .image, completionHandler: {_ in})
func upload(fileUrl: URL, fileData: Data, fileName: String, type: FileTypes, completionHandler: @escaping (URL?) -> ()) {
let expression = AWSS3TransferUtilityUploadExpression()
expression.progressBlock = { task, progress in
DispatchQueue.main.async {
print("Progress = \(progress.completedUnitCount)/\(progress.totalUnitCount)")
}
}
let util = AWSS3TransferUtility.default()
util.uploadData(
fileData,
bucket: self.getBucket(type: type),
key: "\(self.getDir(type: type))_\(fileName)",
contentType: "image/png",
expression: expression) { task, error in
print("ERROR: \(error?.localizedDescription)")
print("response: \(task.response)")
print("response: \(task.response)")
}.continueWith { task in
if let error = task.error {
print("ERROR1: \(error.localizedDescription)")
}
return nil
}
}
它返回给我类似 5 次进度响应的内容,之后
ERROR: Optional("The operation couldn’t be completed. (com.amazonaws.AWSS3TransferUtilityErrorDomain error 2.)")
response: Optional( { URL: http://(bucket).(host)/image_L24i8RGCeAaj.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=59589007eea780cf27c5%2F20200131%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20200131T125453Z&X-Amz-Expires=2999&X-Amz-SignedHeaders=content-type%3Bhost&X-Amz-Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx } { Status Code: 403, Headers { "Content-Length" = ( 186 ); Date = ( "Fri, 31 Jan 2020 12:54:53 GMT" ); Server = ( LeoFS ); } })
具有相同设置的 Android 应用程序可以完美运行。
问题的解决方案是什么?
最佳答案
我也遇到了同样的问题。在 Android 上一切正常,而 IOS 则无法使用相同的配置。
然后我联系了 AWS 支持,他们告诉我 iPhone 的日期和时间错误。我只是将日期和时间调整为正确的日期和时间,然后尝试上传,结果成功。
关于swift - 将文件上传到 S3 服务 403 错误(com.amazonaws.AWSS3TransferUtilityErrorDomain 错误 2。)Swift iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60004473/