关于将照片上传到AWS

时间:2017-12-06 20:45:29

标签: amazon-web-services amazon-s3 aws-step-functions

我正在开发AWS DynamoDB上的软件。我得到了一些UIImages。应该在哪里上传? S3?

我尝试使用S3,但它说我需要将我的照片作为捆绑资源。但我得到的是一个UIImage。

如何将UIImagge转换为NSBUNDLE?

1 个答案:

答案 0 :(得分:1)

您需要设置并执行上传请求:

// Configure the authentication
import AWSS3

// configure S3
let S3BucketName = "<#bucket#>"

// configure authentication with Cognito
let CognitoPoolID = "<#cognito-pool-id#>"
let Region = AWSRegionType.<#region#>
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:Region,
    identityPoolId:CognitoPoolID)
let configuration = AWSServiceConfiguration(region:Region, credentialsProvider:credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration

// Point to the image you want to upload
let ext = "png"
let imageURL = NSBundle.mainBundle().URLForResource("<#image-name#>", withExtension: ext)!

// Setup the upload request
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.body = imageURL
uploadRequest.key = NSProcessInfo.processInfo().globallyUniqueString + "." + ext
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/" + ext

// Push the image
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.upload(uploadRequest).continueWithBlock { (task) -> AnyObject! in
    if let error = task.error {
        print("Upload failed (\(error))")
    }
    if let exception = task.exception {
        print("Upload failed (\(exception))")
    }
    if task.result != nil {
        let s3URL = NSURL(string: "http://s3.amazonaws.com/\(S3BucketName)/\(uploadRequest.key!)")!
        print("Uploaded to:\n\(s3URL)")
    }
    else {
        print("Unexpected empty result.")
    }
    return nil
}

您现在可以通过执行以下操作来创建UIImage实例: let image = UIImage(data:NSData(contentsOfURL:s3URL)!)