dropzone upload file

Let's put the effect picture first

 

1. Introduce the js and css files of dropzone

2.html Here I use a form, of course, you can also use a div directly, no matter what you use, add class="dropzone"

3.js

  1             var fileArr = new Array();
  2             jQuery(function($){
  3                 Dropzone.autoDiscover = false;
  4                 Dropzone.options.myAwesomeDropzone = false;
  5             try {
  6               $(".dropzone").dropzone({
  7                 url:"${pageContext.request.contextPath}/uploadController/upload.action",
  8                 method:"post",
  9                 paramName:"file",
 10                 autoProcessQueue: true ,//Auto upload
 11                  maxFilesize:1024, // MB 
12                  uploadMultiple: false ,
 13                  parallelUploads:10 ,
 14                  acceptedFiles:".rar,.zip,.7z" ,
 15                  dictInvalidFileType:"The supported file types are . rar,.zip,.7z" ,
 16                  addRemoveLinks: true ,
 17              //     maxFiles: //refers to the maximum number of files in the upload directory 
18                  dictRemoveFile: "remove files" ,
 19                 dictUploadCanceled:"Cancel" ,
 20                  dictCancelUploadConfirmation:"Cancel uploading this file?" ,
 21                  dictDefaultMessage:
 22                  " <span class='bigger-150 bolder'><i class='icon-caret-right red'></i> Drag the file</span>upload\
 23                  <span class='smaller-80 gre'>(or click to upload)</span> <br />\
 24                  <i class='upload-icon icon-cloud-upload blue icon-3x'></i>" ,
 25                  dictResponseError: "File upload failed!" ,
 26                  dictFileTooBig: "File too big, upload failed!",
 27                 //change the previewTemplate to use Bootstrap progress bars
 28                 previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-details\">\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n    <div class=\"dz-size\" data-dz-size></div>\n    <img data-dz-thumbnail />\n  </div>\n  <div class=\"progress progress-small progress-striped active\"><div class=\"progress-bar progress-bar-success\" data-dz-uploadprogress></div></div>\n  <div class=\"dz-success-mark\"><span></span></div>\n  <div class=\"dz-error-mark\"><span></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>",
 29                 init:function(){
 30                     this.on("addedfile",function(file,data) {
 31                         fileArr.push(file.upload.uuid);
 32                         //解决点击时重复发送请求
 33                         $(".dz-remove").each(function(index) {
 34                               if(!$(".dz-remove:eq(" + index + ")").attr("id")) {
 35                                   $(".dz-remove:eq(" + index + ")").attr("id",fileArr[index]);
 36                               }
 37                          }) 
 38                          
 39                     })
 40                     this.on("success",function(file,data){
 41                         //var myDropzone = this;
 42                          $("#" + file.upload.uuid).click(function() {
 43                                 var fileName = $(this).parent().find(".dz-filename").text();
 44                                     if(window.confirm("确定要删除吗?")) {
 45                                          $.ajax({
 46                                              type:"POST",
 47                                              url:"${pageContext.request.contextPath}/uploadController/delete.action",
 48                                              data:{"fileName":fileName},
 49                                              dataType:"json",
 50                                              success:function(data){
 51                                                     // this.removeFile(file);
 52                                              }
 53                                          })
 54                                   }  
 55                                 
 56                         })
 57                         
 58                     });
 59                     this.on("sending",function(file,data){
 60                         
 61                     })
 62                     this.on("removedfile",function(file,data){
 63                         
 64                     })
 65                     
 66                       this.on("canceled",function(file,data) {
 67                          // alert("canceled");
 68                          this.removeFile(file);
 69                       }); 
 70                     
 71                     this.on("error",function(file,data){
 72                         
 73                     });
 74                     this.on("complete",function(file) {
 75                             if(file.status == "canceled" || file.status == "error") {
 76                                 var fileName = $("#" + file.upload.uuid).parent().find(".dz-filename").text();
 77                                 setTimeout(function() {
 78                                       $.ajax({
 79                                          type:"POST",
 80                                          url:"${pageContext.request.contextPath}/uploadController/delete.action",
 81                                          data:{"fileName":fileName},
 82                                          dataType:"json",
 83                                          success:function(data){
 84                                              if(data == "success") {
 85                                                 // alert("删除成功");
 86                                             }
 87                                          },
 88                                          error:function(ajax) {
 89                                              alert(ajax.status);
 90                                          }
 91                                     }) 
 92                                 },2000);
 93                         }
 94                     }) 
 95                     
 96                 }
 97               });
 98             } catch(e) {
 99               alert('Dropzone.js does not support older browsers!');
100             }
101             
102         });

Precautions:

1. Regarding parallelUploads, I have read a lot of blogs about this parameter, but I didn't introduce it, so I went to the official website to check it and found that this parameter means the number of file upload queues.

What does it mean? If you set it to 1, but you select multiple files when uploading, then these files will only be uploaded one by one instead of multiple simultaneous uploads

 

3. Backstage

如果你做的时候后台报了异常org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.multipart.MultipartFile]: Specified class is an interface,

请在MultipartFile参数前加上@RequestParam,关于这个注解是起什么作用,自行百度

接收文件

 1 @RequestMapping("/upload")
 2     public String upload(@RequestParam MultipartFile file,HttpSession session){
 3         if(file == null) {
 4             return "";
 5         }
 6         File newFile = null;
 7         InputStream is = null;
 8         BufferedOutputStream bos = null;
 9         BufferedInputStream  bis = null;
10         try {
11             String originalFilename = file.getOriginalFilename();
12             byte[] buffer = new byte[1024];
13             String dirPath = session.getServletContext().getRealPath("/") + "upload";
14             File dir  = new File(dirPath);
15             if(!dir.exists()) {
16                 dir.getParentFile().mkdirs();
17             }
18             if(originalFilename != null && originalFilename.trim().length() > 0) {
19                 newFile = new File(dirPath + "/" + originalFilename);
20             }
21             bos = new BufferedOutputStream(new FileOutputStream(newFile));
22             is  = file.getInputStream();
23           
24             bis = new BufferedInputStream(is);
25             int count = 0;
26             while((count = bis.read(buffer)) != -1){
27                 
28                 bos.write(buffer, 0,count);
29             }
30             bos.flush();
31             
32             String createTime = df.format(System.currentTimeMillis());
33             FileBean fileBean = fileBeanService.findByName(originalFilename);
34             if(fileBean == null) {
35                 fileBean = new FileBean();
36                 fileBean.setName(originalFilename);
37             }
38             fileBean.setCreateTime(df.parse(createTime));
39             fileBeanService.add(fileBean);
40             
41         } catch (FileNotFoundException e1) {
42             e1.printStackTrace();
43         } catch (IOException e) {
44             e.printStackTrace();
45         } catch (ParseException e) {
46             // TODO Auto-generated catch block
47             e.printStackTrace();
48         }finally{
49             if(bis != null){
50                 try {
51                     bis.close();
52                 } catch (IOException e) {
53                     e.printStackTrace();
54                 }
55             }
56             if(bos != null) {
57                 try {
58                     bos.close();
59                 } catch (IOException e) {
60                     e.printStackTrace();
61                 }
62             }
63             
64         }
65         return "redirect:/uploadController/dropzone.action";
66     }

 2.关于移除和取消上传文件

如果你用了数据库,直接把对应的字段改成0就表示此文件不存在,可以不删除

如果你打算真的删除时,执行delete方法前后尽量先让线程睡眠一段时间,否则容易引起IOException,

事实上文件上传过程中点击取消,实现的思路是先把文件上传上来,然后再删除,直接执行删除也有可能引起IOException

ps:这也是3月初的时候用的插件,至今过了一个月了才抽出时间写写总结,在此记录下来给自己一个参考

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325172384&siteId=291194637