下面是從AWS S3存儲桶獲取對象並將對象流寫入servlet響應的代碼。我將內容配置用作「內聯」,因此它直接在瀏覽器上顯示對象。它不會彈出「另存爲」。您可以根據您的要求將其更改爲不同的內容處置方式。
Content disposition
我已經使用了訪問密鑰和祕密密鑰來獲得客戶S3。如果您從可訪問S3存儲桶的EC2運行應用程序,則可將其更改爲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();
}
}
}
}
其實我想知道如何從S3ObjectInputStream中設置javax.servlet.ServletOutputStream,同時從S3獲取圖像。請幫忙。 – vijay