Struts2中的文件下载与在Servlet中下载相似,来回顾一下在Servlet中进行文件下载:
String realpath = ServletActionContext.getServletContext().getRealPath("/download");
try {
FileInputStream fis = new FileInputStream(new File(realpath ,"test.txt");
//设置文件类型
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="+newUser.getFilename());
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len;
while ((len=fis.read(b))!=-1) {
os.write(b, 0, len);
}
os.flush();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
在Struts2中进行下载:
Action中:
public String download() throws Exception {
String id = ServletActionContext.getRequest().getParameter("id");
User newUser = userService.queryById(id);
String path = newUser.getPath();
String fileName = newUser.getFileName();
File file = new File(path, fileName);
FileInputStream fis = new FileInputStream(file);
newUser.setIs(fis);
ActionContext.getContext().getValueStack().push(newUser);
return "download";
}
struts.xml中:
<result name="download" type="stream">
<!-- 对应web中下载配置:application/x-msdownload -->
<param name="contentType">application/x-msdownload</param>
<param name="inputName">is</param>
<!-- 对应web中下载配置:response.setHeader("Content-Disposition", "attachment;filename="+newUser.ge tFilename()); -->
<param name="contentDisposition">attachment;filename=${fileName}</param>
<!-- 对应web中下载配置:byte[] b = new byte[1024]; -->
<param name="bufferSize">1024</param>
</result>
总结:从以上两段代码中不难看出,Struts2中的文件下载只不过是将一些设置放在配置文件中了,文件下载与上传的关键之处就在于准确 的获取文件所在的路径,如果上传或下载的文件名称中带有中文,则需要谨慎处理。