| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

画像出力Servlet

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

画像出力Servlet

Java |

呼出元
<img src="/rscsvr/img.irc?img=01.jpg">
Web.xml
 <servlet>
   <servlet-name>imageresoruce</servlet-name>
   <servlet-class>rc.ImageResourceServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
 </servlet>

 <!-- Standard Action Servlet Mapping -->
 <servlet-mapping>
   <servlet-name>imageresoruce</servlet-name>
   <url-pattern>*.irc</url-pattern>
 </servlet-mapping>
Servlet
package rc;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class ImageResourceServlet extends HttpServlet {
  private String basedir = "c:\\work\\img\\";
  
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    byte[] buf = new byte[1024];

    String img  = request.getParameter("img");
    File f = new File(basedir + img);     

    // 動的ファイルのファイル名を設定
    response.setHeader("Cache-Control", "public"); // IE対策
    response.setContentType("image/jpeg");
    response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");

    FileInputStream r = new FileInputStream(f);

    OutputStream o = response.getOutputStream();
    while (r.read(buf) > 0) {
      o.write(buf);
    }
    o.close();
    r.close();
  }
}