• struts2基于注解的文件下载


    参数说明:

    type = "stream",这里的type一定要等于stream;

    对params的几个参数的解释:

    "contentType", "application/octet-stream" : 文件格式;

    "inputName", "attachstream" :获取文件的方法名;这里的attachstream需要和action里的attachstream对应,类型就是InputStream;

    "contentDisposition", "attachment;filename="${attachname}"":文件内容(显示的)属性,

    这里的filename="${attachname}" :下载之后的文件名;这里需要在action里定义一个变量,去获取下载文件的文件名,包括后缀,例如:下载的文件为**/**/upload/test.jpg,那么需要定义一个变量attachname,变量名一定要对应,然后,attachname = test.jsp;

    "bufferSize", "4096" :限定下载文件 缓冲区的值;

    通过上述属性的解释,我们可以知道,在action里需要定义的变量有以下几个:

    private InputStream attachstream;//文件读取流对象

    private String attachname;//下载文件的名字

    然后需要对应的getter/setter方法,

    action实现代码如下:

     1 @Action(value = "/admin/toDownload",
     2             results = {@Result(name = "download", type = "stream", 
     3                         params = {
     4                         "contentType", "application/octet-stream",
     5                         "inputName", "attachstream",
     6                         "contentDisposition", "attachment;filename="${attachname}"",
     7                         "bufferSize", "4096"
     8             })})
     9     public String toDownload(){
    10         String path = ServletActionContext.getServletContext().getRealPath("/" + fileName);//fileName是页面传过来的参数
    11         try {
    12             attachstream = new FileInputStream(path);
    13             String []attachnames = fileName.split("/");
    14             attachname = attachnames[attachnames.length - 1];
    15         } catch (FileNotFoundException e) {
    16             e.printStackTrace();
    17         }
    18         return "download";
    19     }
  • 相关阅读:
    数据结构:散列函数的构造方法
    数据结构:散列表的基本概念
    数据结构:判断是否为同一棵二叉搜索树
    数据结构:二叉搜索树
    数据结构:二叉树遍历及其递归实现
    数据结构:二叉树遍历及其堆栈实现和应用
    数据结构:二叉树的定义与存储
    poj 2312 Battle City(优先队列+bfs)
    hdu 2112 HDU Today (最短路)
    hdu 1874 畅通工程续
  • 原文地址:https://www.cnblogs.com/xulzong/p/4968706.html
Copyright © 2020-2023  润新知