1、jsp頁面:
<a href="<%=path%>/accessoryFile/download.action?fileName=${flag.fileName}&inputPath=/download/${flag.fileName}">下載</a>
2.struts2.xml
<!-- 附件下載 -->
<action name="download" class="accessoryFileAction"
method="accessoryFileActionMethod">
<result name="success" type="stream">
<param name="contentType">
application/octet-stream;charset=ISO8859-1
</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">
attachment;filename="${downloadFileName}"
</param>
<param name="bufferSize">4096</param>
</result>
<result name="error">/admin/adminError.jsp</result>
</action>
3.action類:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AccessoryFileAction extends ActionSupport
// 附件下找文件名稱
private String fileName;
// 下載路徑
private String inputPath;
//文件下載到客戶時文件名稱
private String downloadFileName;
private InputStream inputStream;
//附件說明
private String fileMsg;
//附件類型及附件名稱
private String typeStr;
//取得IO流
public InputStream getInputStream() throws Exception {
return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
}
/**
* 附件下載方法
*
* @return
*/
public String accessoryFileActionMethod() throws Exception {
// 提供下載的目錄
String downloadDir = ServletActionContext.getServletContext()
.getRealPath("/download");
// 文件下載的路徑
String downloadFile = ServletActionContext.getServletContext()
.getRealPath(inputPath);
// 真實文件路徑
try {
downloadFile = new String(downloadFile.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
System.out.println("轉(zhuǎn)換異常");
}
// 發(fā)現(xiàn)不是指定文件目錄就返回NULL
if (!downloadFile.startsWith(downloadDir)) {
return null;
}
return SUCCESS;
}
/**
* 拼接下載后文件名稱及后綴名
* @return
*/
public String getDownloadFileName() {
String downFileName = fileName;
try {
//用服務(wù)器的文件名作為下載后的文件名
downFileName = new String(downFileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException 異常 ");
}
return downFileName;
}
public String getUploadFileName() {
String temp = new SimpleDateFormat("yyyyMMddhhmmss").format(Calendar.getInstance().getTime()).toString();
return temp+".doc";
}
public void setFileName(String fileName) {
this.fileName = fileName;
try {
fileName = new String(fileName.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
System.out.println("轉(zhuǎn)換異常");
}
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
try {
inputPath = new String(inputPath.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
System.out.println("轉(zhuǎn)換異常");
}
}
get and set 方法略
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。