代码如下:
config.properties 配置文件:
imageUrl=D\:/pages/
action 类:
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.util.ResourceBundle;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.ServletActionContext;public class GetImageAction extends BaseAction{private static final long serialVersionUID = 1L;
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("config"); //获得配置文件对象 private ByteArrayInputStream inputStream; private String fileName; //文件名称 public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public ByteArrayInputStream getInputStream() { return inputStream; } public void setInputStream(ByteArrayInputStream inputStream) { this.inputStream = inputStream; } /** * 获得图片信息 * */ public String getImage() { HttpServletRequest request = ServletActionContext.getRequest(); String ppath = request.getParameter("ppath"); //获得请求时传入的图片文件名 String file = BUNDLE.getString("imageUrl")+ppath;//获得文件路径 try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); InputStream input = new BufferedInputStream(new FileInputStream(file)); byte[] bt = new byte[1024]; while (input.read(bt) > 0) { bos.write(bt); } this.setFileName((System.currentTimeMillis()+ppath.hashCode())+""); //设置图片文件名称 this.inputStream = new ByteArrayInputStream(bos.toByteArray()); bos.close(); input.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return SUCCESS; } }struts.xml配置文件:
<!-- 获得图片信息 -->
<action name="getImage" class="com.xxsb.action.GetImageAction" method="getImage"><!-- 获取文档图片流 -->
<result type="stream"> <param name="contentType">image/jpeg</param> <!-- 文件类型--> <param name="inputName">inputStream</param> <!--图片数据流--> <param name="contentDisposition">filename=${fileName}</param> <!--文件名称--> </result> </action>jsp页面:
<%@ page language="java" pageEncoding="GB2312"%>
<%@ include file="Common/head.jsp"%><!DOCTYPE html><html> <head> <base href="<%=basePath%>" /> <title>xxxxx</title> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3" /> <meta http-equiv="description" content="This is my page" /> </head> <body> <div> <img width="20%" alt="tit" src="<%=request.getContextPath()%>/getImage.action?ppath=11111.jpg"/> </div> </body></html>文件类型的设置和图片名称的设置还可以用response来设置,如下:
HttpServletResponse response = ServletActionContext.getResponse();
response.addHeader("Content-Disposition", "filename=" +fileName);//设置图片文件名称
response.setContentType("image/jpeg"); //设置文件类型差不多就是这样了。