zoukankan      html  css  js  c++  java
  • dropzone上传文件

    先上张效果图吧

    1.引入dropzone的js和css文件

    2.html这里我用了一个form,当然你也可以直接用一个div,无论你用什么都要加上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,//自动上传
     11                 maxFilesize:1024, // MB
     12                 uploadMultiple:false,
     13                 parallelUploads:10,
     14                 acceptedFiles:".rar,.zip,.7z",
     15                 dictInvalidFileType:"支持的文件类型是.rar,.zip,.7z",
     16                 addRemoveLinks:true,
     17             //    maxFiles:   //指的是上传目录下的最大文件数
     18                 dictRemoveFile:"移除文件",
     19                 dictUploadCanceled:"取消",
     20                 dictCancelUploadConfirmation:"取消上传该文件?",
     21                 dictDefaultMessage:
     22                 "<span class='bigger-150 bolder'><i class='icon-caret-right red'></i>拖动文件</span>上传
     23                 <span class='smaller-80 gre'>(或者点击上传)</span> <br /> 
     24                 <i class='upload-icon icon-cloud-upload blue icon-3x'></i>",
     25                 dictResponseError:"文件上传失败!",
     26                 dictFileTooBig:"文件过大,上传失败!",
     27                 //change the previewTemplate to use Bootstrap progress bars
     28                 previewTemplate: "<div class="dz-preview dz-file-preview">
      <div class="dz-details">
        <div class="dz-filename"><span data-dz-name></span></div>
        <div class="dz-size" data-dz-size></div>
        <img data-dz-thumbnail />
      </div>
      <div class="progress progress-small progress-striped active"><div class="progress-bar progress-bar-success" data-dz-uploadprogress></div></div>
      <div class="dz-success-mark"><span></span></div>
      <div class="dz-error-mark"><span></span></div>
      <div class="dz-error-message"><span data-dz-errormessage></span></div>
    </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         });

    注意事项:

    1.关于parallelUploads,这个参数我看了很多博客,都没有介绍,于是我去官网查了下,发现这个参数是文件上传队列数量的意思,

    什么意思呢?如果你设置为1,但你上传的时候选择了多个文件,那么这些文件只会1个1个的上传而不是多个同时上传

    3.后台

    如果你做的时候后台报了异常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月初的时候用的插件,至今过了一个月了才抽出时间写写总结,在此记录下来给自己一个参考

  • 相关阅读:
    照片墙效果一多实例演示【已封装】
    把javascript event事件封装了下,兼容大多数浏览器
    catch error
    call tcl from c
    scrollbar
    sharedlibextension
    treectrl
    get file name part
    namespace eval
    glob
  • 原文地址:https://www.cnblogs.com/tele-share/p/8983180.html
Copyright © 2011-2022 走看看