Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image AWS S3 bucket in swift

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
    }
like image 794
Athila Zuma Avatar asked Oct 31 '16 18:10

Athila Zuma


People also ask

How do I upload pictures to AWS S3?

To upload folders and files to an S3 bucketSign in to the AWS Management Console and open the Amazon S3 console at https://console.aws.amazon.com/s3/ . In the Buckets list, choose the name of the bucket that you want to upload your folders or files to. Choose Upload.

Can I store images in S3 bucket?

You can create a dataset using images stored in an Amazon S3 bucket. With this option, you can use the folder structure in your Amazon S3 bucket to automatically classify your images. You can store the images in the console bucket or another Amazon S3 bucket in your account.

How do you add a picture to a bucket?

In the Google Cloud console, go to the Cloud Storage Buckets page. In the list of buckets, click on the name of the bucket that you want to upload an object to. In the Objects tab for the bucket, either: Drag and drop the desired files from your desktop or file manager to the main pane in the Google Cloud console.


2 Answers

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
}

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
    })
}
}

Thanks :)

like image 38
Karthick Selvaraj Avatar answered Nov 09 '22 13:11

Karthick Selvaraj


AWSS3TransferManager is deprecated. Use AWSS3TransferUtility instead.

The transfer utility provides methods for both single-part and multipart uploads. When a transfer uses multipart upload, the data is chunked into a number of 5 MB parts which are transferred in parallel for increased speed.

 func uploadFile(withImage image: UIImage) {

    let access = "YOUR ACCESS KEY"
    let secret = "YOUR SECRET KEY"
    let credentials = AWSStaticCredentialsProvider(accessKey: access, secretKey: secret)
    let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentials)

    AWSServiceManager.default().defaultServiceConfiguration = configuration

    let s3BucketName = "YOUR BUCKET NAME"
    let compressedImage = image.resizedImage(newSize: CGSize(width: 80, height: 80))
    let data: Data = compressedImage.pngData()!
    let remoteName = generateRandomStringWithLength(length: 12)+"."+data.format
    print("REMOTE NAME : ",remoteName)

    let expression = AWSS3TransferUtilityUploadExpression()
    expression.progressBlock = { (task, progress) in
        DispatchQueue.main.async(execute: {
            // Update a progress bar
        })
    }

   var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
    completionHandler = { (task, error) -> Void in
        DispatchQueue.main.async(execute: {
            // Do something e.g. Alert a user for transfer completion.
            // On failed uploads, `error` contains the error object.
        })
    }

    let transferUtility = AWSS3TransferUtility.default()
    transferUtility.uploadData(data, bucket: s3BucketName, key: remoteName, contentType: "image/"+data.format, expression: expression, completionHandler: completionHandler).continueWith { (task) -> Any? in
        if let error = task.error {
            print("Error : \(error.localizedDescription)")
        }

        if task.result != nil {
            let url = AWSS3.default().configuration.endpoint.url
            let publicURL = url?.appendingPathComponent(S3BucketName).appendingPathComponent(remoteName)
            if let absoluteString = publicURL?.absoluteString {
                // Set image with URL
                print("Image URL : ",absoluteString)
            }
        }

        return nil
    }

}

For generating random strings for remote name.

func generateRandomStringWithLength(length: Int) -> String {
    let randomString: NSMutableString = NSMutableString(capacity: length)
    let letters: NSMutableString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    var i: Int = 0

    while i < length {
        let randomIndex: Int = Int(arc4random_uniform(UInt32(letters.length)))
        randomString.append("\(Character( UnicodeScalar( letters.character(at: randomIndex))!))")
        i += 1
    }
    return String(randomString)
}

For resizing the image and data formatting. Use below Image and Data extensions.

extension UIImage {

  func resizedImage(newSize: CGSize) -> UIImage {
    guard self.size != newSize else { return self }

    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
    self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
    let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return newImage
   }

 }

extension Data {

  var format: String {
    let array = [UInt8](self)
    let ext: String
    switch (array[0]) {
    case 0xFF:
        ext = "jpg"
    case 0x89:
        ext = "png"
    case 0x47:
        ext = "gif"
    case 0x49, 0x4D :
        ext = "tiff"
    default:
        ext = "unknown"
    }
    return ext
   }

}
like image 192
Vinoth Vino Avatar answered Nov 09 '22 12:11

Vinoth Vino