struts2实现批量上传和打包批量下载

struts2框架虽然年久失修,但是作为web后台开发人员,什么框架都得懂点不是,最近研究下载,而struts2框架搭建起来十分容易,就用它实现吧

不得不说,有的框架文档写的十分详细,struts2的框架开发文档写的也不错,

详细解释大偶在代码中

web.xml配置struts2的过滤器,还是简单提一下

   <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

配置一下,上传拦截器中错误信息,采用国际化全局文件:app.zh_CN.properties

这里写图片描述

struts.messages.error.file.too.large=\u4E0A\u4F20\u6587\u4EF6\u592A\u5927\uFF0C\u4E0A\u4F20\u5931\u8D25\uFF01
struts.messages.error.content.type.not.allowed=\u4E0A\u4F20\u6587\u4EF6\u7C7B\u578B\u4E0D\u6B63\u786E\uFF0C\u4E0A\u4F20\u5931\u8D25\uFF01
struts.messages.error.uploading=\u4E0A\u4F20\u5931\u8D25

struts2.xml配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
    "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
<!--     国际化文件开头 -->
    <constant name="struts.custom.i18n.resources" value="app"></constant>
<!--    multipart上传缓存路径 -->
    <constant name="struts.multipart.saveDir" value="F:\cache"></constant>
    <package name="default" namespace="/" extends="struts-default">
<!--     批量上传 -->
            <action name="upload" class="com.leige.action.UploadAction">
                    <result name="success">/index2.jsp</result>
                <result name="input">/index2.jsp</result>
                    <!-- 配置拦截器限制上传文件类型及大小 -->
                    <interceptor-ref name="fileUpload">
                <!--    允许上传的类型 -->
                        <param name="allowedTypes">image/bmp,
                        image/x-png,image/gif,image/jpeg,image/png, image/pjpeg
                        </param>
                        <param name="maximumSize">2097152</param>
                    </interceptor-ref>
                    <interceptor-ref name="defaultStack"></interceptor-ref>
            </action>
        <!--    单个上传 -->
            <action name="loadaction" class="com.leige.action.LoadAction">

                <result name="success" type="stream">
                    <!--    向浏览器说明流信息-->
                  <param name="contentType">application/octet-stream</param>
                         <!--   配置action返回输出流的名称-->
                  <param name="inputName">stream</param>
                         <!-- 配置请求头内容-->
                  <param name="contentDisposition">attachment;filename="${filename}"</param>
                         <!-- 配置缓存大小-->
                  <param name="bufferSize">1024*1024</param>
                </result>
            </action>
        <!--    批量打包下载 -->
                <action name="BatchLoadAction" class="com.leige.action.BatchLoadAction">

                <result name="success" type="stream">
                  <param name="contentType">application/octet-stream</param>
                  <param name="inputName">stream</param>
                  <param name="contentDisposition">attachment;filename="file.zip"</param>
                  <param name="bufferSize">1024*1024</param>
                </result>
            </action>
    </package>


</struts>

前台页面编写

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
//错误信息显示
  ${msg }
///  国际化错误显示
  <s:fielderror></s:fielderror>
  批量上传
  <form action="<%=basePath %>/upload.action" method="post" enctype="multipart/form-data">
  <input type="file" name="file">
    <input type="file" name="file">
      <input type="file" name="file">
        <input type="file" name="file">
  <input type="submit" value="上传">
  </form>

  <hr/>
  批量下载
   <form action="<%=basePath%>/BatchLoadAction.action" method="get">
        <input type="checkbox"  name="filename" value="img1.jpg">Image2
        <input type="checkbox"  name="filename" value="img2.jpg">Image3
        <input type="checkbox"  name="filename" value="img3.jpg">Image4
        <input type="submit" value="下载">
     </form> 

     单个文件下载:
         <a href="<%=basePath%>/loadaction.action?filename=易宝.png">下载</a>
  </body>
</html>

批量上传action代码

package com.leige.action;

import java.io.File;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class UploadAction extends ActionSupport {
/*  strut2中文件上传的定义规则是,
 * file:表单文name属性
 * fileFileName:文件名称
 * fileContentType:文件类型
 * */
    //接收文件
    private List<File> file;
    //接收文件名称
    private String[] fileFileName;
    //接收文件类型
    private String[] fileContentType;




    public List<File> getFile() {
        return file;
    }




    public void setFile(List<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;
    }
//实现上传
    @Override
    public String execute() throws Exception {
        String path=ServletActionContext.getServletContext().getRealPath("/img");
    try{

        for(int i=0;i<file.size();i++){ 
            FileUtils.copyFile(file.get(i),new File(path,fileFileName[i]));
        }
    }catch (Exception e) {
        //出现异常自动返回input视图
        ActionContext.getContext().put("msg", "上传失败");
    return "input";
    }
        ActionContext.getContext().put("msg", "上传成功");
        return "success";
    }

}

struts2单个文件下载,action代码:

package com.leige.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoadAction extends ActionSupport {

        private String filename;
        private InputStream stream;
        public String getFilename() {
            return filename;
        }
        public void setFilename(String filename) {
            this.filename = filename;
        }
        public InputStream getStream() {
            return stream;
        }           

        @Override
        public String execute() throws Exception {
        //获取下载路径
        String path=ServletActionContext.getServletContext().getRealPath("/img");
        //下载文件路径,文件名称重新编码,处理中文问题,当然如果配置了全局过滤器,就不用处理
          File downFile=new File(path,new String(filename.getBytes("ISO-8859-1"),"UTF-8"));       
             if(!downFile.exists()){
                 ActionContext.getContext().put("msg", "亲,您要下载的文件不存在");
                 return "success";
             }else{
                  //返回文件流信息
                stream = new FileInputStream(downFile);
                ActionContext.getContext().put("msg", "下载成功");
                return "success";
             }
        }


}

struts2多个文件批量打包下载,核心使用就是压缩流ZipOutputStream:

package com.leige.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BatchLoadAction extends ActionSupport{
      //批量下载
      private List<String> filename;
      private InputStream stream;


    public List<String> getFilename() {
        return filename;
    }
    public void setFilename(List<String> filename) {
        this.filename = filename;
    }
    public InputStream getStream() {
        return stream;
    }

    @Override
    public String execute() throws Exception {
    //获取下载路径
    String path=ServletActionContext.getServletContext().getRealPath("/img");
     //注释换行符
        String str = "";
        String rt = "\r\n";
        //指定缓存路径
        File zipFile=new File(path,"temp.zip");
        //先把文件进行本地缓存
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile) );  
    for(int i=0;i<filename.size();i++){
            //下载文件路径,文件名称重新编码,处理中文问题,当然如果配置了全局过滤器,就不用处理
          String filenameChild=new String(filename.get(i).getBytes("ISO-8859-1"),"UTF-8");
           File downFile = new File(path,filenameChild);
            if(!downFile.exists()){
                     ActionContext.getContext().put("msg", "亲,您要下载的文件不存在");
                     return "success";
                 }else{
                     //生成注释
                    str += filenameChild + rt;
                    zos.putNextEntry(new ZipEntry(filename.get(i)));
                    FileInputStream fis = new FileInputStream(downFile);
                    //复制文件到压缩流中
                    IOUtils.copy(fis, zos);     
                    zos.flush();
                    fis.close();
                 }       
    }

                //设置注释,执行到这里说明压缩流已生成
                zos.setComment("下载成功:" + rt +  new String(str.getBytes("UTF-8"),"GBK"));
                zos.flush();
                zos.close();
                stream=FileUtils.openInputStream(zipFile);
                //删除缓存文件
                if(zipFile.exists())zipFile.delete();

      ActionContext.getContext().put("msg", "下载成功");
        return "success";
    }


}

代码还有好多问题没有考虑到,打包下载时,有明显的延迟,可能是后台进行文件压缩耗时太长,不知道各位有什么解决办法没有

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值