springBoot+webUploader文件分片上传

webUploader

是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件

官方文档链接:(http://fex.baidu.com/webuploader/)

前端代码

var uploader = WebUploader.create({
   	 auto: true,// 选完文件后,是否自动上传。
     swf: 'webUpload/Uploader.swf',// swf文件路径
     server: '上传地址',// 文件接收服务端。
     dnd: '#upload-container',
     // formData: {name:'222'},
     pick: '#upload-btn',// 内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的id
     multiple: false, // 选择多个
     chunked: true,// 开起分片上传。
     threads: 10, // 上传并发数。允许同时最大上传进程数。
     method: 'POST', // 文件上传方式,POST或者GET。
     fileNumLimit: 1,//可上传文件数量
     fileSizeLimit: 50 * 1024 * 1024, //验证文件总大小是否超出限制, 超出则不允许加入队列。
     fileSingleSizeLimit: 50 * 1024 * 1024, //验证单个文件大小是否超出限制, 超出则不允许加入队列。
     fileVal: 'upload', // [默认值:'file'] 设置文件上传域的name。
     // 只允许选择图片文件。
     accept: {
         title: 'pdf',
         extensions: 'pdf',
         mimeTypes: 'application/pdf'
     }
 });


 //单个文件 加入队列前
 uploader.on('beforeFileQueued', function (file) {
     uploader.reset();    //重置队列文件
 });


 //文件队列
 uploader.on('fileQueued', function (file) {
     /*
         选中文件时要做的事情,
         比如在页面中显示选中的文件并添加到文件列表,
         获取文件的大小,文件类型等
         console.log(file.ext) // 获取文件的后缀
         console.log(file.size) // 获取文件的大小
     */
     console.log(file);

     //如果他小于100kb
     if (file.size < 1024 * 100) {
         uploader.options.chunkSize = 1024 * 20
     }

     //如果他小于100kb小于300kb
     if (file.size > 100 * 1024 && file.size < 300 * 1024) {
         uploader.options.chunkSize = 1024 * 50
     }

     //如果他小于300kb小于1Mb
     if (file.size > 300 * 1024 && file.size < 1240 * 1024) {
         uploader.options.chunkSize = 1024 * 200
     }

     //如果他大于1Mb小于5Mb
     if (file.size > 1024 * 1024 && file.size < 5 * 1024 * 1024) {
         uploader.options.chunkSize = 1024 * 1024
     }

     //如果他大于5Mb小于10Mb
     if (file.size > 5 * 1024 * 1024 && file.size < 10 * 1024 * 1024) {
         uploader.options.chunkSize = 1024 * 1024 * 2
     }

     //如果他大于10Mb
     if (file.size > 10 * 1024 * 1024) {//如果他大于1Mb
         uploader.options.chunkSize = 1024 * 1024 * 5
     }

     if (file.ext != 'pdf') {
         uploader.reset();    //重置队列文件
         layer.alert("请选择pdf文件")
     }
     if ((50 * 1024 * 1024) < file.size) {
         uploader.reset();    //重置队列文件
         layer.alert("文件大于50mb")
     }
 });


 //上传完成
 uploader.on('uploadSuccess', function (file, response) {
     // console.log(file.id + "传输成功");
     if (response.state == 1){
          layer.alert(response.msg)
     }
 });

 uploader.on('uploadError', function (file) {
     console.log(file);
     console.log(file.id + 'upload error')
 });


 uploader.on('uploadComplete', function (file) {
     console.log(uploader.getFiles());
 }); 

后端代码

public String upload(HttpServletRequest req, MultipartFile file) {
       JSONObjectResult reJson = new JSONObjectResult();
       CustomUserDetails user = UserUtil.getCurrentUser();
       //本地文件存放路径
       String uploadPath = fileStorageService.getFileStorageLocation() + File.separator + "fileView"
               + File.separator + "zbcl" + File.separator + user.getUsername();

       Integer chunk = null;       //当前分片
       Integer chunks = null;      //分片总数
       String name = null;         //文件名

       //文件输出缓存流
       BufferedOutputStream os = null;
       try {
           req.setCharacterEncoding(ENCODING);

           if (!req.getParameter("chunk").isEmpty()) {//当前分片
               chunk = Integer.parseInt(req.getParameter("chunk"));
           }

           if (!req.getParameter("chunks").isEmpty()) {//分片总数
               chunks = Integer.parseInt(req.getParameter("chunks"));
           }

           if (!req.getParameter("name").isEmpty()) {//文件名
               name = req.getParameter("name");
           }

           //创建文件目录
           File uploadTemp = new File(uploadPath);
           if (!uploadTemp.exists()) {
               uploadTemp.mkdirs();
           }

           try {
               //分片文件名
               String chunkFileName = chunk + DELIMITER + name;
               File chunkFile = new File(uploadPath + File.separator + chunkFileName);
               if (!chunkFile.exists()) {
                   file.transferTo(chunkFile);
               }
           } catch (IOException e) {
               e.printStackTrace();
               System.out.println("分片上传错误:" + chunk + “-” + name);
               reJson.setState(0);
               reJson.setMsg("分片上传失败");
               return reJson.toString();
           }


           //本地存储文件名
           SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
           String fileName = sdf.format(new Date()) +  “-”  + name;

           if (chunk != null && chunk.intValue() == chunks.intValue() - 1) {
               try {
                   //存放到本地文件的路径
                   File targetTempFile = new File(uploadPath + File.separator + fileName);
                   os = new BufferedOutputStream(new FileOutputStream(targetTempFile));

                   for (int i = 0; i < chunks; i++) {//循环本地分片文件
                       File chunkFile = new File(uploadPath, i +  “-” + name);
                       while (!chunkFile.exists()) {
                           System.out.println("分片文件不存在:" + i +  “-” + name);
                           Thread.sleep(100);
                       }
                       byte[] buffer = FileUtil.readAsByteArray(chunkFile);
                       os.write(buffer);
                       os.flush();
                       chunkFile.delete();
                   }
                   os.flush();

                   reJson.setState(1);
                   reJson.setMsg("文件上传成功");
                   JSONObject reData = new JSONObject();
                   reData.put("fileName", name.substring(0, name.lastIndexOf(".")));
                   reData.put("filePath", "fileView/zbcl/" + user.getUsername() + "/" + fileName);
                   reJson.setResults(reData);

                   return reJson.toString();
               } catch (FileNotFoundException e) {
                   e.printStackTrace();
                   System.out.println("未找到本地分片文件:" + chunk +  “-” + name);
               } catch (InterruptedException e) {
                   e.printStackTrace();
                   System.out.println("休眠失败");
               } catch (IOException e) {
                   e.printStackTrace();
                   System.out.println("分片合并文件失败:" + chunk +  “-” + name);
               }
           }

           reJson.setState(0);
           reJson.setMsg("正在上传");
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
           reJson.setState(0);
           reJson.setMsg("上传异常");
       } finally {
           try {
               if (os != null) {
                   os.close();
                   System.out.println("流已关闭");
               }
           } catch (IOException e) {
               e.printStackTrace();
               System.out.println("os关闭失败");
           }

       }
       return reJson.toString();
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值