简体   繁体   中英

Uploading Image to S3 Bucket - Java SDK

I am working on an iOS application which connects to my Tomcat/Jersey server.

The way I am currently uploading images to S3 is using the following workflow:
- upload image to a temp folder on my server using a POST request Multipart Form data
- take the file from the temp folder and using the Amazon Java SDK I upload it to S3
- delete the image file from the temp folder on the server once upload is completed to S3

I do not want my iOS app to upload directly to S3 as I want to go through my server to perform some operations but in my opinion this seems redundant and will make the process slower than it may need to be. Is there a way to stream the file directly through the Amazon SDK instead of having to temp save it to my server?

Thanks for the suggestions. I used your answers to solve it by uploading the Input Stream directly through the Amazon SDK like so:

byte[] contents = IOUtils.toByteArray(inputStream);
InputStream stream = new ByteArrayInputStream(contents);

ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(contents.length);
meta.setContentType("image/png");

s3client.putObject(new PutObjectRequest(
        bucketName, fileName, stream, meta)
        .withCannedAcl(CannedAccessControlList.Private));

inputStream.close();

Where inputStream is the input stream received from the iOS application to my server and s3client is the AmazonS3Client initialization with the BasicAWSCredentials .

You can get the InputStream by using HttpServletRequest .getInputStream() to save the input stream into a data member then pass it on to the S3 SDK: Execute one of the AmazonS3Client.putObject overloads depending on whether you are uploading data from a file, or a stream. from the Amazon S3 .

after the upload finishes successfully/with error, you can return a relevant response to the user.

let me know if you need anymore help.

If you just want to protect the S3 upload behind some authentication mechanism, you could generate a pre-signed S3 upload url after the user has been authenticated, then you could upload directly to S3 from iOS using that URL. That would meet your authentication requirements but keep all the upload traffic off your web server.

This is a very common design pattern for allowing users to upload files to S3 after authentication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM