I've looked many amazon docs but didn't find enough information to upload and download images to S3 using Swift.
How can I do that?
我看过很多亚马逊文档,但是没有找到足够的信息来上传和下载图片到S3使用Swift。我怎么做呢?
2 个解决方案
#1
9
After doing many research I've got this working,
在做了很多研究之后,我成功了,
import AWSS3
import AWSCore
Upload:
上传:
I assume you have implemented UIImagePickerControllerDelegate
already.
我想你已经实现了UIImagePickerControllerDelegate。
Step 1:
步骤1:
-
Create variable for holding url:
创建保存url的变量:
var imageURL = NSURL()
-
Create upload completion handler obj:
创建上传完成处理程序obj:
var uploadCompletionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
Step 2: Get Image URL from imagePickerController(_:didFinishPickingMediaWithInfo:)
:
步骤2:从imagePickerController获取图像URL (_:didFinishPickingMediaWithInfo:):
-
Set value of
imageURL
in this delegate method:在此委托方法中设置imageURL的值:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){ //getting details of image let uploadFileURL = info[UIImagePickerControllerReferenceURL] as! NSURL let imageName = uploadFileURL.lastPathComponent let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String // getting local path let localPath = (documentDirectory as NSString).stringByAppendingPathComponent(imageName!) //getting actual image let image = info[UIImagePickerControllerOriginalImage] as! UIImage let data = UIImagePNGRepresentation(image) data!.writeToFile(localPath, atomically: true) let imageData = NSData(contentsOfFile: localPath)! imageURL = NSURL(fileURLWithPath: localPath) picker.dismissViewControllerAnimated(true, completion: nil) }
Step 3: Call this uploadImage
method after imageURL
set to Upload Image to your bucket:
步骤3:在imageURL设置后调用这个uploadImage方法,将图像上传到您的bucket:
func uploadImage(){
//defining bucket and upload file name
let S3BucketName: String = "bucketName"
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)")
})
}
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.uploadFile(imageURL, 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;
}
}
Download:
下载:
func downloadImage(){
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
let S3BucketName: String = "bucketName"
let S3DownloadKeyName: String = "public/testImage.jpg"
let expression = AWSS3TransferUtilityDownloadExpression()
expression.downloadProgress = {(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)")
})
}
completionHandler = { (task, location, data, error) -> Void in
dispatch_async(dispatch_get_main_queue(), {
if ((error) != nil){
print("Failed with error")
print("Error: \(error!)")
}
else{
//Set your image
var downloadedImage = UIImage(data: data!)
}
})
}
let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
transferUtility.downloadToURL(nil, bucket: S3BucketName, key: S3DownloadKeyName, expression: expression, completionHander: completionHandler).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("Download Starting!")
}
return nil;
}
}
引用上传图片
引用下载图片
Many thanks to jzorz
非常感谢jzorz
#2
0
If all you want is to download the image, this is a much more concise and correct way to do it:
如果你只想下载图片,这是一种更简洁、更正确的方式:
func downloadImage(bucketName: String, fileName: String, completion: (image: UIImage?, error: NSError?) -> Void) {
let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
transferUtility.downloadDataFromBucket(bucketName, key: fileName, expression: nil) { (task, url, data, error) in
var resultImage: UIImage?
if let data = data {
resultImage = UIImage(data: data)
}
completion(image: resultImage, error: error)
}
}
#1
9
After doing many research I've got this working,
在做了很多研究之后,我成功了,
import AWSS3
import AWSCore
Upload:
上传:
I assume you have implemented UIImagePickerControllerDelegate
already.
我想你已经实现了UIImagePickerControllerDelegate。
Step 1:
步骤1:
-
Create variable for holding url:
创建保存url的变量:
var imageURL = NSURL()
-
Create upload completion handler obj:
创建上传完成处理程序obj:
var uploadCompletionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
Step 2: Get Image URL from imagePickerController(_:didFinishPickingMediaWithInfo:)
:
步骤2:从imagePickerController获取图像URL (_:didFinishPickingMediaWithInfo:):
-
Set value of
imageURL
in this delegate method:在此委托方法中设置imageURL的值:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){ //getting details of image let uploadFileURL = info[UIImagePickerControllerReferenceURL] as! NSURL let imageName = uploadFileURL.lastPathComponent let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String // getting local path let localPath = (documentDirectory as NSString).stringByAppendingPathComponent(imageName!) //getting actual image let image = info[UIImagePickerControllerOriginalImage] as! UIImage let data = UIImagePNGRepresentation(image) data!.writeToFile(localPath, atomically: true) let imageData = NSData(contentsOfFile: localPath)! imageURL = NSURL(fileURLWithPath: localPath) picker.dismissViewControllerAnimated(true, completion: nil) }
Step 3: Call this uploadImage
method after imageURL
set to Upload Image to your bucket:
步骤3:在imageURL设置后调用这个uploadImage方法,将图像上传到您的bucket:
func uploadImage(){
//defining bucket and upload file name
let S3BucketName: String = "bucketName"
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)")
})
}
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.uploadFile(imageURL, 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;
}
}
Download:
下载:
func downloadImage(){
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
let S3BucketName: String = "bucketName"
let S3DownloadKeyName: String = "public/testImage.jpg"
let expression = AWSS3TransferUtilityDownloadExpression()
expression.downloadProgress = {(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)")
})
}
completionHandler = { (task, location, data, error) -> Void in
dispatch_async(dispatch_get_main_queue(), {
if ((error) != nil){
print("Failed with error")
print("Error: \(error!)")
}
else{
//Set your image
var downloadedImage = UIImage(data: data!)
}
})
}
let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
transferUtility.downloadToURL(nil, bucket: S3BucketName, key: S3DownloadKeyName, expression: expression, completionHander: completionHandler).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("Download Starting!")
}
return nil;
}
}
引用上传图片
引用下载图片
Many thanks to jzorz
非常感谢jzorz
#2
0
If all you want is to download the image, this is a much more concise and correct way to do it:
如果你只想下载图片,这是一种更简洁、更正确的方式:
func downloadImage(bucketName: String, fileName: String, completion: (image: UIImage?, error: NSError?) -> Void) {
let transferUtility = AWSS3TransferUtility.defaultS3TransferUtility()
transferUtility.downloadDataFromBucket(bucketName, key: fileName, expression: nil) { (task, url, data, error) in
var resultImage: UIImage?
if let data = data {
resultImage = UIImage(data: data)
}
completion(image: resultImage, error: error)
}
}