struts2 word、excel文件的下载
后台action
因为我在数据库中的文件名中存取的是,一段路径+文件名称。所以我第一步是要从该路径中取出文件的名称。
以“/”截取字符
String[] strings=实体类.getFilename().split("/");
for (int i = 0; i < strings.length; i++) {
判断截取的字符中是否含有“.”。
if(strings[i].contains(".")){
存在的话就获取到文件的名称了。
this.setFileName(strings[i]);
}
}
return "success"; 到配置文件中。
<action name="FileDownload" class="org.action. FileDownloadAction"
method="doFileDownload">
<result name="success"
type="stream">
<param name="contentType">application/msword,application/vnd.ms-excel</param>
<param name="contentDisposition">attachment;filename="${fileName}"</param>
attachment作用是:弹出的那个 保存,取消的框。
<param name="bufferSize">4096</param>
<param name="inputName">
downLoadFile【 封装好的方法。即:FileDownloadAction中的getDownLoadFile()方法
】</param>
读取到这里后在进入FileDownloadAction中的
getDownLoadFile()方法。
【getDownLoadFile()Struts2封装好的方法】
public InputStream getDownLoadFile() throws IOException {
try {
String tmpName = filePath + this.getFileName();
File file = new File(tmpName);
if(file.exists()) {
InputStream inputStream=new FileInputStream(filePath + this.getFileName());
return inputStream;
}
else {
HttpServletResponse response=ServletActionContext.getResponse();
response.sendRedirect("fileNotFound.jsp");
}
} catch (Exception e) {
LOG.info("file download error!");
e.printStackTrace();
}
return null;
}
</result>
</action>
以上就是我在做文件下载时的一些问题。。如有疑问欢迎提出。。