標籤:
=============================struts 檔案下載 ==================================
步驟一: JSP頁面
<a href="download.action?fileName=IMG_0443.JPG">點擊此處下載圖片</a>
步驟二: Action頁面
package org.zm.action;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownLoadAction extends ActionSupport{
//讀取下載檔案的目錄
private String inputPath;
//下載檔案的檔案名稱
private String fileName;
//讀取下載檔案的輸入資料流
private InputStream inputStream;
//下載檔案的類型
private String conetntType;
//建立InputStream輸入資料流
public InputStream getInputStream() throws FileNotFoundException{
String path=ServletActionContext.getServletContext().
getRealPath(inputPath);
return new BufferedInputStream(new FileInputStream(path+"\\"+
fileName));
}
@Override
public String execute() {
return SUCCESS;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getConetntType() {
return conetntType;
}
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public void setConetntType(String conetntType) {
this.conetntType = conetntType;
}
}
步驟三: Struts.xml檔案
<action name="download" class="org.zm.action.DownLoadAction">
<param name="inputPath">/upload</param>
<result name="success" type="stream">
<param name="contentType">image/pjpeg</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="bufferSize">4096</param>
</result>
</action>
提示: Stream結果類型
contentType: 設定發送到瀏覽器的MIME類型
contentLength: 檔案大小
contentDisposition: 設定響應的HTTP頭資訊的Content-Disposition參數的值
inputName: 指定Action提供的inputStream類型的屬性名稱
bufferSize:設定讀取和下載檔案時緩衝區的大小
struts.xml檔案和Action 這兩處位置的變數名稱一定要正確。
struts 檔案下載