Upload Base64 encoded images to Amazon S3 using java

I'm trying to upload files to Amazon S3 storage using Amazon's Java API Code is

Byte[] b = data.getBytes();
InputStream stream  = new ByteArrayInputStream(b);
//InputStream stream = new FileInputStream(new File("D:/samples/test.txt"));
AWSCredentials credentials = new BasicAWSCredentials("<key>","<key1>");
AmazonS3 s3client = new AmazonS3Client(credentials);
s3client.putObject(new PutObjectRequest("myBucket",name,stream,new ObjectMetadata()));

When I run the code after commenting on the first two lines and uncommenting the third line, that is, the stream is fileoutputstream, the file is uploaded correctly However, when the data is Base64 encoded string (i.e. image data), the file will be uploaded, but the image is damaged Amazon documentation says I need to create and attach post policies and signatures to use How can I do this in Java? I didn't use HTML form to upload

Solution

First, you should delete the data from the beginning of the string: image / PNG; base64:

Sample code block:

byte[] bI = org.apache.commons.codec.binary.Base64.decodeBase64((base64Data.substring(base64Data.indexOf(",")+1)).getBytes());

InputStream fis = new ByteArrayInputStream(bI);

AmazonS3 s3 = new AmazonS3Client();
Region usWest02 = Region.getRegion(Regions.US_WEST_2);
s3.setRegion(usWest02);
ObjectMetadata Metadata = new ObjectMetadata();
Metadata.setContentLength(bI.length);
Metadata.setContentType("image/png");
Metadata.setCacheControl("public,max-age=31536000");
s3.putObject(BUCKET_NAME,filename,fis,Metadata);
s3.setObjectAcl(BUCKET_NAME,CannedAccessControlList.PublicRead);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>