Displaying an image stored in amazon s3 on the web browser using servlet
I have stored my images开发者_JAVA百科 in S3.
What I have -
The input stream containing the image.
What I want?
Design a servlet which can convert this input stream into an image.
Please help. I am new to all this.
The easiest thing to do is to use the S3 urls directly.
For public files they are in the format:
http://s3.amazonaws.com/[bucket]/[key]
But, as @T.J. points out in his answer, those images will then be externally visible.
However, you can make your content private so it is not reachable by the standard url and only via a signed, expiring url. The java AWS SDK will make it easy to create these.
Your servlet will receive a response
parameter which is a ServletResponse
instance, which has a getOutputStream
method. Use setContentType
to set content type of the response as appropriate for the image data, use getOutputStream
to get an output stream, and then loop, reading from your input stream and writing to your output stream.
Alternately, if it suits what you're doing (and it may or may not), you can have the img
tag in your HTML point directly to the image in s3 and avoid streaming it through your server entirely. But of course, that only works if you're okay with the image being externally-reachable. If you search for "s3 serve image" you'll find various articles (including one by SO's own Jeff Atwood) about doing this, I won't randomly pick one to link here.
In html
<img src='setImageFromS?path=sample/file&fileName=image.jpg'>
In Servlet
public void setImageFromS3(HttpServletRequest request, HttpServletResponse response) {
File tmp = null;
try {
// create a client connection based on credentials
AmazonS3 s3client = new AmazonS3Client(getAWSCredentials());
String bucketName = getS3BucketName();
String fileName = "";
// upload file to folder and set it to public
fileName = request.getParameter("path") +"/" + request.getParameter("fileName");
S3Object o = s3client.getObject(bucketName, fileName);
S3ObjectInputStream s3is = o.getObjectContent();
tmp = File.createTempFile("s3test", ".jpeg");
Files.copy(s3is, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
BufferedImage image = ImageIO.read(tmp);
ImageIO.write(image, "jpeg", jpegOutputStream);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
tmp.delete();
byte[] imgByte = jpegOutputStream.toByteArray();
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(imgByte);
responseOutputStream.flush();
responseOutputStream.close();
} catch (IOException ex) {
Logger.getLogger(AmazonS3DaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return true;
}
精彩评论