在swift中上传图像AWS S3存储桶 [英] Upload image AWS S3 bucket in swift

查看:275
本文介绍了在swift中上传图像AWS S3存储桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像上传到存储桶S3 AWS,我正在使用以下代码。但我是否使用它上传到存储在变量或imageView.image中的图像?

I'm trying to upload an image to a bucket S3 AWS, I am using the following code. but do I use it to upload to an image stored in a variable or imageView.image?

let ext = "jpg"
    let imageURL = NSBundle.mainBundle().URLForResource("imagename", withExtension: ext)
    print("imageURL:\(imageURL)")

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


    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/\(self.S3BucketName)/\(uploadRequest.key!)")!
            print("Uploaded to:\n\(s3URL)")
        }
        else {
            print("Unexpected empty result.")
        }
        return nil
    }


推荐答案

我修改了你的代码,试试这个

I Have modified your code, try this

 let ext = "jpg"
let imageURL = NSBundle.mainBundle().URLForResource("imagename", withExtension: ext)
print("imageURL:\(imageURL)")

let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest.body = imageURL
uploadRequest.key = "\(NSProcessInfo.processInfo().globallyUniqueString).\(ext)"
uploadRequest.bucket = S3BucketName
uploadRequest.contentType = "image/\(ext)"


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/\(self.S3BucketName)/\(uploadRequest.key!)")!
print("Uploaded to:\n\(s3URL)")
}
else {
print("Unexpected empty result.")
}
return nil
}

或者您可以使用我的代码上传到AWS s3,它对我来说很好。此代码用swift 3编写。

or you can use my code below to upload to AWS s3, its worked fine for me. This code is written in swift 3.

func uploadButtonPressed(_ sender: AnyObject) {
if documentImageView.image == nil {
   // Do something to wake up user :) 
} else {
    let image = documentImageView.image!
    let fileManager = FileManager.default
    let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("\(imageName!).jpeg")
    let imageData = UIImageJPEGRepresentation(image, 0.99)
    fileManager.createFile(atPath: path as String, contents: imageData, attributes: nil)

    let fileUrl = NSURL(fileURLWithPath: path)
    var uploadRequest = AWSS3TransferManagerUploadRequest()
    uploadRequest?.bucket = "BucketName"
    uploadRequest?.key = "key.jpeg"
    uploadRequest?.contentType = "image/jpeg"
    uploadRequest?.body = fileUrl as URL!
    uploadRequest?.serverSideEncryption = AWSS3ServerSideEncryption.awsKms
    uploadRequest?.uploadProgress = { (bytesSent, totalBytesSent, totalBytesExpectedToSend) -> Void in
        DispatchQueue.main.async(execute: {
            self.amountUploaded = totalBytesSent // To show the updating data status in label.
            self.fileSize = totalBytesExpectedToSend
        })
    }

    let transferManager = AWSS3TransferManager.default()
    transferManager?.upload(uploadRequest).continue(with: AWSExecutor.mainThread(), withSuccessBlock: { (taskk: AWSTask) -> Any? in
        if taskk.error != nil {
           // Error.
        } else {
            // Do something with your result.
        }
        return nil
    })
}
}

谢谢:)

这篇关于在swift中上传图像AWS S3存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆