Struts2实现文件下载(使用注解的方式)

    xiaoxiao2023-03-24  2

    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  //是缓冲区的字节数

    转载请注明原文地址: https://ju.6miu.com/read-1200214.html
    最新回复(0)