Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
11
Help us understand the problem. What is going on with this article?
@endrugus

Tomcatで画像ファイル表示

More than 5 years have passed since last update.

色々試してみましたが、このコードで安定したのでメモです。
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>
11
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
endrugus
いちおう、組み込み系です。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
11
Help us understand the problem. What is going on with this article?