1. 程式人生 > >struts項目向前臺返回圖片。

struts項目向前臺返回圖片。

etl ati 圖片 struts2 讀取 tor lose pan apach

讀取項目路徑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項目向前臺返回圖片。