10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tomcatで画像ファイル表示

Posted at

色々試してみましたが、このコードで安定したのでメモです。
Tomcat: 7.0.53

まずはサーブレットのコード。

ImageFileServlet
package com.sample.web;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/imagefile")
public class ImageFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ImageFileServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //出力するファイル(あらかじめWebContent以下に配置しておく。)
        String dir = getServletContext().getRealPath("/");
        String fname = request.getParameter("name");

        int iData = 0;

        //ServletのOutputStream取得
        ServletOutputStream out = response.getOutputStream();

        //画像ファイルをBufferedInputStreamを使用して読み取る
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(dir+fname));

        //画像を書き出す
        while((iData = in.read()) != -1){
            out.write(iData);
        }

        in.close();
        out.close();
    }

}

続いて表示用のHTML

test.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Servletで画像ファイル表示</title>
</head>
<body>
<img src="./imagefile?name=neko2.jpg"><br>
<img src="./imagefile?name=neko2.png"><br>
<img src="./imagefile?name=neko2.gif"><br>
</body>
</html>
10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?