文件下载
1. 在Servlet中的文件下载是通过流来实现的
2. 在struts2中也可以通过流来实现下载。实现方式和Servlet实现方式相同,注意在action中执行方法里返回null。
Action代码
publicclass DownloadAction { public String execute() throws IOException{ HttpServletRequest request=ServletActionContext.getRequest(); HttpServletResponse response=ServletActionContext.getResponse(); String path=request.getRealPath("/download"); //这里把文件写死了 File file=new File(path,"lesson2_JDBC.rar"); response.setCharacterEncoding("utf-8"); response.setContentLength((int)file.length()); response.setHeader("Content-Disposition", "attachment;filename=lesson2_JDBC.rar");
InputStream is=new FileInputStream(file); //通过response获得输出流 OutputStream os=response.getOutputStream(); byte[] buffer=newbyte[512]; intlen=0; while((len=is.read(buffer))!=-1){ os.write(buffer, 0, len); } os.close(); is.close(); returnnull; } } |
struts.xml
<!-- 当action返回结果为空时,不需要配置结果集 --> <action name="download" class="com.zys.action.DownloadAction"> </action> |
JSP页面
<body> <a href="download.action">下载lesson2_JDBC.rar文件</a> </body> |
3. 使用struts2本身结果集来进行下载
StreamDownloadAction类
publicclass StreamDownloadAction {
private String fileName;
public String execute(){ return"success"; }
public InputStream getInputStream() throws FileNotFoundException{ HttpServletRequest request=ServletActionContext.getRequest(); String path=request.getRealPath("/download"); File file=new File(path,fileName); FileInputStream fis=new FileInputStream(file); returnfis; }
publicvoid setFileName(String fileName) { this.fileName = fileName; } //get方法可以获得通过URL传参的值 public String getFileName() { returnfileName; } } |
JSP页面
<body> <a href="streamdown.action?fileName=lesson2_JDBC.rar">下载文件</a> </body> |
struts.xml
<action name="streamdown" class="com.zys.action.StreamDownloadAction"> <result type="stream"> <param name="contentDisposition">attachment;filename=${fileName}</param> </result> </action> |
注意:如果在result中配置inputName参数的值,那么action中要生成相应的get方法。