Как обслуживать образ, хранящийся на моем жестком диске, в сервлете?
Например:
У меня есть изображение, сохраненное в пути 'Images/button.png'
, и я хочу служить в сервлете с URL file/button.png
.
Вывод файла изображения из сервлета
Ответ 1
- отобразить сервлет в
/file
url-pattern - прочитать файл с диска
- записать его в
response.getOutputStream()
- установите заголовок
Content-Type
наimage/png
(если это только pngs)
Ответ 2
Вот рабочий код:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ServletContext cntx= req.getServletContext();
// Get the absolute path of the image
String filename = cntx.getRealPath("Images/button.png");
// retrieve mimeType dynamically
String mime = cntx.getMimeType(filename);
if (mime == null) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
resp.setContentType(mime);
File file = new File(filename);
resp.setContentLength((int)file.length());
FileInputStream in = new FileInputStream(file);
OutputStream out = resp.getOutputStream();
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
out.write(buf, 0, count);
}
out.close();
in.close();
}
Ответ 3
Вот еще один очень простой способ.
File file = new File("imageman.png");
BufferedImage image = ImageIO.read(file);
ImageIO.write(image, "PNG", resp.getOutputStream());