struts2文件上传及下载

文件上传
  • 单文件上传

    • struts2的文件上传功能通过commons-fileupload来实现
  • jsp表单需要为post提交,并且enctype="multipart/form-data"

    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>Upload</title>
        </head>
        <body>
            <form action="upload.action" method="post" enctype="multipart/form-data">
                file:<input type="file" name="file"/>
                <br>
                <input type="submit" value="upload"/>
            </form>
        </body>
    </html>
  • ation的代码中

    • 需要提供三个属性:
      • File类型,名称为表单域名
      • String类型,名称为表单域名 + FileName
      • String类型,名称为表单域名 + ContentType(可用于限制可上传文件的类型)
    • 提供get/set方法
    • 实例代码
public class UploadAction extends ActionSupport{
    private File file;
    //文件名
    private String fileFileName; // input name + "FileName"
    private String fileContentType; // input name + "ContentType"

    //上传文件
    public String upload() throws IOException {
        HttpServletRequest request = ServletActionContext.getRequest();
        String path = request.getRealPath("/upload");
        InputStream is = new FileInputStream(file);
        OutputStream os = new FileOutputStream(new File(path, fileFileName));

        byte[] buffer = new byte[200];
        int len = 0;
        while((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        }

        os.close();
        is.close();

        System.out.println(path);
        return Action.SUCCESS;
    }

    public File getFile() {
        return file;
    }
    public void setFile(File file) {
        this.file = file;
    }
    public String getFileFileName() {
        return fileFileName;
    }
    public void setFileFileName(String fileFileName) {
        this.fileFileName = fileFileName;
    }
    public String getFileContentType() {
        return fileContentType;
    }
    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }
}
  • struts.xml配置文件:
    • 需要配置constant属性struts.multipart.maxSize
    • 拦截器中需要引用fileUpload,并且设置maximumSize参数
    • maxSize >= maximumSize
    • 实例代码
<struts>
    <constant name="struts.multipart.saveDir" value="/Users/chenyu/Desktop"/>
    <!-- 设置上传文件的最大大小,必须大于maximumSize -->
    <constant name="struts.multipart.maxSize" value="20971520"/>

    <package name="default" extends="struts-default">
        <action name="upload" class="com.eric.action.UploadAction" method="upload">
            <result>/index.jsp</result>
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">20971520</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"/>
        </action>
    </package> 
</struts>
  • 批量文件上传
  • struts2可以将批量的文件处理为数组,上传到action中

  • jsp代码:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Upload</title>
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            $(function() {
                $('#btn').click(function() {
                    var field = "<p><input type='file' name='file'/><input type='button' value='remove' onclick='cancel(this);'/><p>";
                    $('#files').append(field);
                });
            });  

            function cancel(o) {
                $(o).parent().remove();
            }
        </script>
    </head>
    <body>
        <form action="batch.action" method="post" enctype="multipart/form-data">
            file:<input type="file" name="file"/>
            <input type="button" id="btn" value="add"/>
            <div id="files"></div>
            <input type="submit" value="upload"/>
        </form>
    </body>
</html>
  • action处理代码基本和单个文件上传基本一致(只需要使用循环将文件从数组中取出)
public String execute() throws IOException {
    HttpServletRequest request = ServletActionContext.getRequest();
    String path = request.getRealPath("/upload");

    for(int i = 0; i < file.length; i++) {
        InputStream is = new FileInputStream(file[i]);
        OutputStream os = new FileOutputStream(new File(path, fileFileName[i]));

        byte[] buffer = new byte[200];
        int len = 0;
        while((len = is.read(buffer)) != -1) {
            os.write(buffer, 0, len);
        } 

        System.out.println(path);
        os.close(); 
        is.close();
    }

    return Action.SUCCESS;
}

文件下载
  • 在servlet中的文件下载通过流来实现
  • 在sturts2中实现文件下载:

    • 通过实现:

      public class DownloadAction {
          public String execute() throws IOException {
              HttpServletRequest request = ServletActionContext.getRequest();
              HttpServletResponse response = ServletActionContext.getResponse();
      
              //获取路径
              String path = request.getRealPath("/download");
      
              //获取文件
              File file = new File(path, "back_to_the_sea-wallpaper-2880x1800.jpg");
              response.setContentLength((int) file.length());
              response.setCharacterEncoding("utf-8");
              response.setContentType("application/octet-stream");
              response.setHeader("Content-Disposition", "attachment;filename='back_to_the_sea-wallpaper-2880x1800.jpg'");
      
              byte[] buffer = new byte[400];
              int len = 0;
      
              InputStream is = new FileInputStream(file);
              OutputStream os = response.getOutputStream();
      
              while((len = is.read(buffer)) != -1) {
                  os.write(buffer, 0, len);
              }
      
              os.close();
              is.close();
      
              return null; // 返回结果为null,不需要配置result
          }
      }
    • 通过struts2的结果集实现:

      • action代码

        public class StreamDownloadAction {
            private String fileName;
            public String execute() {
                return Action.SUCCESS;
            }
            //获取输入流,方法名和配置文件的inputName要一致
            public InputStream getInputStream() throws IOException {
                HttpServletRequest request = ServletActionContext.getRequest();
                String path = request.getRealPath("/download");
                return new FileInputStream(new File(path, fileName));
            }
            public String getFileName() {
                return fileName;
            }
            public void setFileName(String fileName) {
                this.fileName = fileName;
            }
        }
      • 配置文件

        <!-- 使用结果集实现下载 -->
        <action name="streamDownload" class="com.eric.action.StreamDownloadAction">
            <result type="stream">
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">attachment;filename=${fileName}</param>
            </result>
        </action>
        • <result type="stream">结果集会执行stream对应的java类,对文件输入流进行处理,从而实现文件下载
        • <param name="inputName">需要和action类中的文件流获取方法一致
        • <param name="contentDisposition">需要定义
      • jsp页面

        <html>
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                <title>Index</title>
            </head>
            <body>
                <a href="streamDownload.action?fileName=spiderman_homecoming_2017-wallpaper-5120x3200.jpg" download="图片">picture</a>
            </body>
        </html>
        • 通过请求中的参数,传递fileName,action中通过fileName创建对应的FIle类并返回输入流
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值