将图片作为流直接输出到浏览器

时间:2022-10-21 13:13:34

  <%
   // 如果你想将输出包含在一个jsp中,可以用img标签调用本jsp
   // <img src="pic.jsp?from=file&type=jpeg&src=c:/img/test.jpg">
  
   // 图片来源, 从文件(file)或数据库(database)
   String from = request.getParameter("from") == null ? "" : request.getParameter("from").toString();
  
   // 图片类型, jpeg/gif/bmp
   String type = request.getParameter("type") == null ? "" : request.getParameter("type").toString();
   response.reset();
   response.setContentType("image/" + type);
  
   java.io.InputStream in = null;
  
   // 方式1: 以流方式读取图片文件. pic.jsp?from=file&type=jpeg&file=c:/img/test.jpg
   if ( from.equals("") || from.equals("file") )
   {
   in = new java.io.FileInputStream(request.getParameter("src").toString());
   }
   else // 方式2: 从数据库中读取流. pic.jsp?from=database&type=jpeg&src=168
   {
   java.util.List list = DbWrapper .executeQuery(
   "select CONTENT from IMAGE where id = '" + request.getParameter("src").toString() + "'"
   );
  
   if ( list.size() > 0 )
   {
   in = (InputStream)(((java.util.Map)list.get(0)).get("CONTENT"));
   }
   }
   if ( in != null )
   {
   byte[] b = new byte[1024];
   int len;
   while( (len = in.read(b)) != -1 )
   {
   response.getOutputStream().write(b);
   }
  
   in.close();
   }
  %>