我正在使用以下代码从AWS S3存储桶下载映像。
com.amazonaws.services.s3.model.S3Object object = s3Client.getObject(new
GetObjectRequest(bucketName, mediaItem.getFileName()));
S3ObjectInputStream objectData = object.getObjectContent();
object.close();
return objectData.toString();
我得到了200个回复,但在imageview中它没有显示图像。
答案 0 :(得分:0)
以下是从AWS S3存储桶获取对象并将对象流写入servlet响应的代码。我使用内容处理作为“内联”,因此它直接在浏览器上显示对象。它不会弹出“另存为”。您可以根据需要将其更改为不同的内容处理。
我使用了访问密钥和密钥来获取s3客户端。如果从EC2运行可以访问S3存储桶的应用程序,则可以将其更改为InstanceProfileCredentialsProvider
(即注释代码)。
public class GetS3Object extends HttpServlet {
private static final long serialVersionUID = -3924600769478978726L;
private static Logger logger = Logger.getLogger(GetS3Object.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletOutputStream out = resp.getOutputStream();
/*AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new InstanceProfileCredentialsProvider(false)).build();*/
BasicAWSCredentials awsCreds = new BasicAWSCredentials("accesskey", "secretkey");
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
try {
GetObjectRequest getObjectRequest = new GetObjectRequest("yourbucketName", "objectkey");
S3Object s3Object = s3Client.getObject(getObjectRequest);
byte[] s3Content = org.apache.commons.io.IOUtils.toByteArray(s3Object.getObjectContent());
resp.setHeader("Content-Type",
getServletContext().getMimeType(s3Object.getObjectMetadata().getContentType()));
resp.setHeader("Content-Length", String.valueOf(s3Content.length));
resp.setHeader("Content-Disposition", "inline; filename=\"" + "Google_logo.jpeg" + "\"");
out.write(s3Content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
out.flush();
out.close();
}
}
}
}