struts项目向前台返回图片。
Posted valarchie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts项目向前台返回图片。相关的知识,希望对你有一定的参考价值。
读取项目路径WebRoot下的图片
编写action
package com.sadj.market.action; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.logging.Logger; import com.opensymphony.xwork2.util.logging.LoggerFactory; public class PublicAction extends ActionSupport{ //定义输出到前台的输出流 private ByteArrayInputStream imageStream; private Logger logger=LoggerFactory.getLogger(Public.class); private static final long serialVersionUID = 1L; public String image() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); //获取webroot下的文件 String path = request.getSession().getServletContext().getRealPath("/")+"statics\\x.jpg"; System.out.println(path); //创建文件输入流 FileInputStream fis = new FileInputStream(path); //放入bufferedInputStream BufferedInputStream bis=new BufferedInputStream(fis); //定义ByteArrayOutStream ByteArrayOutputStream output = new ByteArrayOutputStream(); int c=bis.read();//读取bis流中的下一个字节 while(c!=-1){ output.write(c); c=bis.read(); } bis.close(); imageStream = new ByteArrayInputStream(output.toByteArray()); return SUCCESS; } public ByteArrayInputStream getImageStream() { return imageStream; } public void setImageStream(ByteArrayInputStream imageStream) { this.imageStream = imageStream; } }
编写struts.xml
<action name="image" class="com.sadj.market.action.PublicAction" method="image"> <result name="success" type="stream"> <param name="contentType">image/jpeg</param> <param name="inputName">imageStream</param> <param name="bufferSize">2048</param> </result> </action>
前台直接访问image这个action即可
以上是关于struts项目向前台返回图片。的主要内容,如果未能解决你的问题,请参考以下文章