使用AWS Swift SDK将图像上传到S3

0 amazon-s3 amazon-web-services ios swift aws-sdk

我正在尝试使用 AWS Swift SDK 中的 putObject 方法将图像上传到 S3 存储桶。我已按照此处的说明进行操作:https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/examples-s3-objects.html

我可以将字符串添加到 s3 存储桶,但不知道如何添加图像。我尝试将图像转换为 jpegdata 和 pngdata,但无济于事。

这是我的代码:

//      AWS S3 image upload
        func uploadFile(withImage image: UIImage) {
            let s3Client = try? S3Client(region: "us-west-2")

            let bucketName = "xxxxx"
            let imageData = image.pngData()
            guard let dataToUpload = "Text to upload working".data(using: .utf8) else {
                return
            }
            let body = ByteStream.from(data: imageData!)
            s3Client!.putObject(input: PutObjectInput(body: body, bucket: bucketName, contentType: "image/png", key: "Test")) { result in
                switch(result) {
                case .success(let response):
                    if let eTag = response.eTag {
                        print("Successfully uploaded the file with the etag: \(eTag)")
                    }
                case .failure(let err):
                    print(err)
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

如果我将“dataToUpload”放入 ByteStream.from 函数中,数据将存储在 s3 存储桶中。但是,如果我使用图像数据,则不会。

对任何和所有解决方案开放,谢谢!

Sai*_*yas 6

您还可以用于AWSS3TransferUtility将文件上传到S3

脚步

1)在上传之前或仅通过此方法在您的应用程序委托中设置存储桶凭据setupCreditial()

  1. 使用uploadFileToS3源视图中的方法将文件上传到 s3

      /** regionType is your bucket region name identityPoolId is your bucket unique id*/
    
     func setupCreditial(){
    
    
         let credentialProvider = AWSCognitoCredentialsProvider(regionType: .AFSouth1, identityPoolId: "YourPoolID")
         let config = AWSServiceConfiguration.init(region: .AFSouth1, credentialsProvider: credentialProvider)
    
         AWSServiceManager.default().defaultServiceConfiguration = config
         AWSS3TransferUtility.register(with: config!, forKey: "NAMEOFUTILITY")
     }
     /*
      key is your aws3 key where you want to put image . in most cases it would public/key where key = any udid
      content type is is file type like image,pdf,word etc
      **/
     public func uploadFileToS3(withKey key : String , contentType type : String, andData data : Data) {
         let awsUploadExp = AWSS3TransferUtilityUploadExpression()
         awsUploadExp.progressBlock = {task ,progress in
             //progress goes here
         }
         guard   let transferUtililty  = AWSS3TransferUtility.s3TransferUtility(forKey: "NAMEOFUTILITY") else{
             return
         }
         let completionHandler : AWSS3TransferUtilityUploadCompletionHandlerBlock = {(task,error)-> Void in
             //handle your completion
         }
    
         transferUtililty.uploadData(data, bucket: "YourBucketname", key: key, contentType: type, expression: awsUploadExp, completionHandler: completionHandler)
     }
    
    Run Code Online (Sandbox Code Playgroud)