在作項目中上傳下載確定是少不了的,本博文對struts2的下載進行解釋並附上部分代碼 一、action類
public class FileDownLoadAction extends ActionSupport{
private String filename;//下載文件的名稱
@Override
public String execute() throws Exception {
return SUCCESS;
}
//下載源
public InputStream getInputStream() throws IOException{
String path =ServletActionContext.getServletContext().getRealPath(filename);//獲取文件路徑
//System.out.println("path="+path);
File file = new File(path);
return FileUtils.openInputStream(file);
}
//下載文件名
public String getDownloadFileName() throws Exception{
String downloadFileName="";
String []filenames=filename.split("/");
//System.out.println(filenames[filenames.length-1]);
downloadFileName=URLEncoder.encode(filenames[filenames.length-1], "UTF-8");//解決下載中文命名文件亂碼問題
return downloadFileName;
}
///////////////////////////////////////////字段封裝//////////////
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}
二、struts2.xml配置
<action name="download" class="com.zzuli.student.action.FileDownLoadAction">
<!--以流的方式返回 -->
<result name="success" type="stream">
<!--文件流 -->
<param name="contentType">application/octet-stream</param>
<!--下載源 -->
<param name="inputName">InputStream</param>
<!--以附件方式下載 downloadFileName相應Action類getDownloadFileName() -->
<param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
<!--緩衝流大小 -->
<param name="bufferSize">8192</param>
</result>
三、jsp下載連接頁面
<td>
<a href="download.action?filename=${documentUrl}">點擊下載</a>
</td>
具體具體解釋請查看Struts官方文檔