1. struts2配置文件:
<result name="testsuccess" type="stream">
<!-- 聲明下載時存儲文件流的變量名 -->
<param name="inputName">testStream</param>
<param name="contentType">application/octet-stream;charset=GBK</param>
<!-- fileName 爲Action類中定義的私有變量,用於存儲下載文件時顯示的文件名 -->
<param name="contentDisposition">
attachment;filename="${fileName}"
</param>
<param name="bufferSize">4096</param>
</result>
說明:
result標籤中需要定義 type=”stream” 。
在Action中只需要定義 testStream 的get方法即可,即getTestStream(),不需要定義private InputStream testStream這樣的類私有變量。
2.Action中:
@Controller("downloadAction")
@Scope("prototype")
public class DataDownloadAction extends ActionSupport {
//用戶存儲下載時顯示的文件名
private String fileName;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public InputStream getTestStream() throws Exception {
String filename = "中文書名測試.pdf";
String filepath = "E:\\book\\"+filename;
File file = new File(filepath);
InputStream inStream = null;
inStream = new FileInputStream(file);
//需要轉換纔可以顯示中文文件名
this.fileName = new String(filename.getBytes(), "ISO8859-1");
return inStream;
}
}
說明:
如果文件名爲中文,需要在給fileName定義時進行字符集轉換:this.fileName = new String(filename.getBytes(), “ISO8859-1”);
此外,tomcat的字符集需要設置爲UTF-8,具體方法爲編輯conf/server.xml中添加URIEncoding=”UTF-8”
<Connector port="8080" protocol="HTTP/1.1"
maxThreads="150" connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8"/>