再说说文件下载,文件下载的一个简单的方法是在页面中设置href(超链接),地址就是文件的路径。
例:
<a href="/portal/upload/temp/文件名.txt"/>下载</td>
路径是Tomcat下工程中webapp内的路径,如果路径下有文件,则会提供下载。
但这样做隐患很多,最大的是txt和图片文件浏览器会对他自动打开。
所以这里说说用struts2自带的工具提供下载。
也是加入一个href,链接地址是action。
例:
<a href="/portal/common/download.action?fileType=00&fileid=106"/>下载</td>
其中因为我的文件名和路径在数据库有存储,所以我在这里只返回一个fileid,fileType用于分辨文件类型,当不同功能共同使用这个接口用于文件下载时用到。
FIleDownloadAction:
public class FileDownloadAction extends BaseAction {
private String fileName;
private InputStream inputStream;
WpsTmpFileService wpsTmpFileService;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName)
throws UnsupportedEncodingException {
this.fileName = new String(fileName.getBytes("iso8859-1"), "utf-8");
}
public void setWpsTmpFileService(WpsTmpFileService wpsTmpFileService){
this.wpsTmpFileService = wpsTmpFileService;
}
public String download() throws UnsupportedEncodingException {
String sFileid = servletRequest.getParameter("fileid");
String fileType = servletRequest.getParameter("fileType");
WpsTmpFileDTO fileDTO =null;
// 查询数据库并验证文件是否存在
if(sFileid ==null){
servletRequest.setAttribute("errormsg", "文件id不存在");
return ERROR;
}
if(fileType==null){
servletRequest.setAttribute("errormsg", "文件类型不存在");
return ERROR;
}
else if("00".equals(fileType)){
fileDTO = wpsTmpFileService.getFileById(sFileid);
}
if(fileDTO==null){
servletRequest.setAttribute("errormsg", "文件不存在");
return ERROR;
}
String fName = fileDTO.getSavename();
// 解解乱码
this.fileName = new String(fName.getBytes("GBK"), "ISO-8859-1");
String fileDir =fileDTO.getUploaddir()+fileDTO.getFilename();
// String fd = "/upload/temp/201608191807268591.txt";
try{
this.inputStream = ServletActionContext.getServletContext()
.getResourceAsStream(fileDir);
System.out.println(this.inputStream);
}
catch(Exception e){
e.printStackTrace();
}
if (inputStream ==null) {
servletRequest.setAttribute("errormsg", "文件不存在或已被删除");
return ERROR;
}
return SUCCESS;
}
public InputStream getDownloadFile()
{
return inputStream;
}
}
struts.xml:
<action name="download" class="fileDownload" method="download">
<result name="error">/WEB-INF/pages/workspace/error.jsp</result>
<result name="success" type="stream">
<param name="contentDisposition">attachment;fileName="${fileName}"</param>
<param name="inputName">downloadFile</param>
<param name="bufferSize">1024</param>
</result>
</action>