首页 > 代码库 > struts项目向前台返回图片。
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项目向前台返回图片。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。