swift - amazon S3 Swift - 简单的上传需要很长时间,最终没有出现在桶中

标签 swift file-upload amazon-s3

我正在尝试在 S3 存储桶上发送照片。好吧,这在 swift 中真是太糟糕了,sdk 到处都是零散的,这对我来说是一团糟,到目前为止没有任何效果:

我的上传过程继续进行,但速度非常慢(假设一张 5 兆的图像需要 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()

}

明确地说,我的图像数据 NSData 来自 uiimage,从 collectionviewcell 中获取:

 self.imagedata = UIImageJPEGRepresentation(img!, 05.0)!

有什么我可以更新以了解我哪里错了吗? 提前致谢:)

最佳答案

好的,正在尝试使用 uploaddata 请求上传 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 年,但由于这段清晰且评论良好的代码,我可以轻松地转换它

关于swift - amazon S3 Swift - 简单的上传需要很长时间,最终没有出现在桶中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35376577/

相关文章:

找不到 iOS Metal 默认库

php file_put_contents 函数不起作用

java - 如何使用 URI 创建 java.io.File 对象?

amazon-web-services - 访问受限于 VPC 端点的 S3 网站从 VPC 内部获取 403

javascript - 将 ArrayBuffer 发送到 S3 放入 signedURL

node.js - 通过 Express 服务器从 S3 流式传输音频需要太长时间

ios - Scenekit - 基于世界轴的旋转子子节点的 convertTransform

ios - 导航栏按钮图像像素化

ios - Swift:无法使用 NSLayoutConstraint 在 Superview 中居中 UIView

C# - 将数据库中保存的文件附加到电子邮件中