我正在尝试使用Amazon的
Java API将文件上传到Amazon S3存储.代码是
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()));
当我在评论前两行并取消注释第三行后运行代码,即stream是FileoutputStream时,文件被正确上载.但是当数据是base64编码的字符串(即图像数据)时,文件会上传但图像已损坏.
亚马逊文档说我需要创建并附加POST策略和签名才能使用.我怎么能在java中做到这一点?我没有使用html表单进行上传.
解决方法
首先你应该从字符串的开头删除数据:image / png; base64:
示例代码块:
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);