配置struts.xml
<?xml version="1.0"encoding="gbk"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD StrutsConfiguration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 設置Web應用的默認編碼集爲gbk -->
<constant name="struts.i18n.encoding"value="gbk" />
<!-- 設置Web應用的默認Locale爲zh_CN-->
<constant name="struts.locale" value="zh_CN"/>
<!-- 設置Struts2.1應用的國際化資源文件,多個文件中間可用逗號分隔-->
<constant name="struts.custom.i18n.resources"value="MessageResource,globalMessage" />
<!--設置Struts2.1應用是否處於開發模式,通常在開發調試階段設爲true,正式上線後可設爲false-->
<constant name="struts.devMode" value="true"/>
<!-- 設置Struts2.1的默認主題爲simple-->
<constant name="struts.ui.theme" value="simple"/>
<!-- 設置上傳文件臨時文件夾 -->
<constant name="struts.multipart.saveDir"value="/tmp" />
<package name="book" extends="struts-default"namespace="/">
<action name="filedownload"class="com.book.struts.action.FileDownloadAction">
<result name="success"type="stream"> <!--定義相關參數 -->
<paramname="contentType">${contenttype}</param>
<paramname="inputName">inputStream</param>
<paramname="bufferSize">4096</param>
<paramname="contentDisposition">attachment;filename=${filename}</param> </result>
</action>
</package>
</struts>
<!----------------------------下載文件Action--------------------------->
package com.book.struts.action;
import java.io.FileNotFoundException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownloadAction extends ActionSupport {
private String inputpath; // 下載文件路徑
private String contenttype; // 文件類型
private String filename; // 文件名
// 返回一個InputStream類型
public java.io.InputStream getInputStream() throwsFileNotFoundException {
returnServletActionContext.getServletContext().getResourceAsStream(inputpath);
}
@SuppressWarnings("deprecation")
@Override
public String execute() throws Exception {
// 調用相關業務邏輯方法 動態設置下載信息
inputpath = "\\WEB-INF\\images\\0.jpg";
contenttype = "image/jpeg";
// 解決下載的中文文件名問題
filename = java.net.URLEncoder.encode("文件.jpg","utf-8");
return SUCCESS;
}
public String getContenttype() {
return contenttype;
}
public void setContenttype(String contenttype) {
this.contenttype = contenttype;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getInputpath() {
return inputpath;
}
public void setInputpath(String inputpath) {
this.inputpath = inputpath;
}
}
<!---------------------------注意事項--------------------------------!>
在struts.xml中配置下載文件入口,也就是<paramname="inputName">inputStream</param>
假如inputName的值不是inputStream 而是xxxx,那麼在下載的Action中要有一個返回類型爲InputStream,
方法名爲getXxxx的方法。
例如:public InputStreamgetXxxx(){
returnServletActionContext.getServletContext().getResourceAsStream(inputpath);
}
如果不能下載並出這樣的異常Can not find a java.io.InputStream with the name[inputStream] in the invocation stack. Check the<param name="inputName"> tagspecified for this action.
請看上一遍文章。