Struts2对文件的下载做了很优雅的处理,配置起来很简单,使用也很方便。
下载流程概览:
HttpRequest ---> "downLoad---> SUCCESS Result --> 输出流
//实现文件下载 private String fileName; private String mimeType; private InputStream inStream; public InputStream getInStream() { return inStream; } public void setInStream(InputStream inStream) { this.inStream = inStream; } public String getFileName() { try { return new String(fileName.getBytes(),"ISO8859-1"); } catch (UnsupportedEncodingException e) { return this.fileName; } } public void setFileName(String fileName) { this.fileName = fileName; } public String getMimeType() { return mimeType; } /*** * 实现文件下载 * @param * @return SUCCESS * @throws DaoException */ @Action(value="/dbbak/downLoad", results={ @Result(name="SUCCESS",params={ "contentType", "${mimeType}", "inputName", "inStream", "contentDisposition", "attachment;filename=\"${fileName}\"", "bufferSize", "4096" },type="stream") }) public String downLoad()throws DaoException{ //获取目录下的前五个dmp文件名 String path = HwUtils.getRequest().getRealPath("/") + "dbbak"; mimeType = HwUtils.getServletContext().getMimeType(getFileName()); System.out.println(mimeType); inStream = HwUtils.getServletContext().getResourceAsStream("/dbbak/" + fileName); if (inStream == null) { inStream = new ByteArrayInputStream("Sorry,File not found !".getBytes()); } return SUCCESS; } 这里解释一下,返回stream类型需要配置的参数
contentType //可以有servletContext 获得
inputstream //这里对应的是我们声明的inputStream的名字
contentDisposition //是下载文件的描述,主要用于赋值下载文件的名字
bufferSize //是缓冲区的字节数