java读取本地图片并在jsp中显示

源:http://blog.csdn.net/yzh54ak/article/details/5875435

评:非原文,修改测试正确

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        try {
            System.out.println("aa");
            showPicture(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showPicture(HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        //String picId = request.getParameter("picId");
        String pic_path = "D:\\psb.png";
        System.out.println(pic_path);
        FileInputStream is = new FileInputStream(pic_path);
        int i = is.available(); // 得到文件大小
        byte data[] = new byte[i];
        is.read(data); // 读数据
        is.close();
        response.setContentType("image/*"); // 设置返回的文件类型
        OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
        toClient.write(data); // 输出数据
        toClient.close();
    }

 

web.xml

    <servlet>
   <servlet-name>Picture</servlet-name>
   <servlet-class>Picture</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>Picture</servlet-name>
   <url-pattern>/showPicture</url-pattern>
</servlet-mapping>

 

index.jsp

<%
String path = request.getContextPath();
%>

 <img src="<%=path %>/showPicture"> 

你可能感兴趣的:(java)