我正在尝试在 S3 存储桶上发送照片。好吧,这是 swift 中没有记录的地狱,sdk 到处都是碎片化的,这对我来说是一团糟,到目前为止没有任何效果:
我的上传过程还在继续,但非常慢(假设一张 5 meg 的图像需要 10 分钟(,而且大多数时候,上传会冻结并重新开始。
但奇怪的是,当它最终成功时,该文件没有出现在我的存储桶中。我尝试将文件上传到不存在的存储桶,但该过程仍在继续(???(
这是我的凭据 LOC (存储桶在东加州(
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType: AWSRegionType.USEast1, identityPoolId: "us-east-1:47e88493-xxxx-xxxx-xxxx-xxxxxxxxx")
let defaultServiceConfiguration = AWSServiceConfiguration(
region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration
现在这是我的上传功能
func uploadImage(){
//defining bucket and upload file name
let S3BucketName: String = "witnesstestbucket"
let S3UploadKeyName: String = "public/testImage.jpg"
let expression = AWSS3TransferUtilityUploadExpression()
expression.uploadProgress = {(task: AWSS3TransferUtilityTask, bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) in
dispatch_async(dispatch_get_main_queue(), {
let progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
print("Progress is: (progress)")
print (Float(totalBytesExpectedToSend))
})
}
self.uploadCompletionHandler = { (task, error) -> Void in
dispatch_async(dispatch_get_main_queue(), {
if ((error) != nil){
print("Failed with error")
print("Error: (error!)");
}
else{
print("Sucess")
}
})
}
let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
transferUtility.uploadData(imagedata, bucket: S3BucketName, key: S3UploadKeyName, contentType: "image/jpeg", expression: expression, completionHander: uploadCompletionHandler).continueWithBlock { (task) -> AnyObject! in
if let error = task.error {
print("Error: (error.localizedDescription)")
}
if let exception = task.exception {
print("Exception: (exception.description)")
}
if let _ = task.result {
print("Upload Starting!")
}
return nil;
}
}
@IBAction func post(sender: UIButton) {
// AW S3 upload
uploadImage()
}
为了清楚起见,My imagedata NSData 来自一个 uiimage,从 collectionviewcell 获取:
self.imagedata = UIImageJPEGRepresentation(img!, 05.0)!
有什么我可以更新以了解我错在哪里吗?提前致谢:)
好的,正在尝试使用上传数据请求上传 NSData 文件,这是具有正确 URL swift2 转换的工作代码:
func uploadImage(){
let img:UIImage = fullimage!.image!
// create a local image that we can use to upload to s3
let path:NSString = NSTemporaryDirectory().stringByAppendingString("image2.jpg")
let imageD:NSData = UIImageJPEGRepresentation(img, 0.2)!
imageD.writeToFile(path as String, atomically: true)
// once the image is saved we can use the path to create a local fileurl
let url:NSURL = NSURL(fileURLWithPath: path as String)
// next we set up the S3 upload request manager
uploadRequest = AWSS3TransferManagerUploadRequest()
// set the bucket
uploadRequest?.bucket = "witnesstest"
// I want this image to be public to anyone to view it so I'm setting it to Public Read
uploadRequest?.ACL = AWSS3ObjectCannedACL.PublicRead
// set the image's name that will be used on the s3 server. I am also creating a folder to place the image in
uploadRequest?.key = "foldername/image2.jpeg"
// set the content type
uploadRequest?.contentType = "image/jpeg"
// and finally set the body to the local file path
uploadRequest?.body = url;
// we will track progress through an AWSNetworkingUploadProgressBlock
uploadRequest?.uploadProgress = {[unowned self](bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.amountUploaded = totalBytesSent
self.filesize = totalBytesExpectedToSend;
print(self.filesize)
print(self.amountUploaded)
})
}
// now the upload request is set up we can creat the transfermanger, the credentials are already set up in the app delegate
let transferManager:AWSS3TransferManager = AWSS3TransferManager.defaultS3TransferManager()
// start the upload
transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject? in
// once the uploadmanager finishes check if there were any errors
if(task.error != nil){
print("%@", task.error);
}else{ // if there aren't any then the image is uploaded!
// this is the url of the image we just uploaded
print("https://s3.amazonaws.com/witnesstest/foldername/image2.jpeg");
}
return "all done";
}
}
我要感谢Barrett Breshears的帮助,他的GithubSource来自2014年,但由于这段清晰且注释良好的代码,我可以轻松转换它