服务器之家

服务器之家 > 正文

webuploader 实现图片批量上传功能附实例代码

时间:2021-02-24 12:57     来源/作者:Hawk喵

1、导入资源

webuploader 实现图片批量上传功能附实例代码

 

webuploader 实现图片批量上传功能附实例代码

2、jsp代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<div class="page-container">
    <div class="row cl">
      <label class="form-label col-xs-4 col-sm-2"><span
        class="c-red">*</span>项目名称:</label>
      <div class="formcontrols col-xs-8 col-sm-9">
        <input type="text" class="input-text" value="${proname }"
          placeholder="" id="" name="proname" readonly="readonly">
      </div>
    </div>
    <div class="row cl">
      <label class="form-label col-xs-4 col-sm-2">缩略图:</label>
      <div class="formcontrols col-xs-8 col-sm-9">
        <div class="uploader-thum-container">
          <div id="filelist" class="uploader-list"></div>
          <div id="filepicker">选择图片</div>
          <button id="btn-star"
            class="btn btn-default btn-uploadstar radius ml-10">开始上传</button>
        </div>
      </div>
    </div>
    <div class="row cl">
      <label class="form-label col-xs-4 col-sm-2"><span
        class="c-red">*</span>项目发票上传:</label>
      <div class="formcontrols col-xs-8 col-sm-9">
        <div class="uploader-list-container">
          <div class="queuelist">
            <div id="dndarea" class="placeholder">
              <div id="filepicker-2"></div>
              <p>或将照片拖到这里,单次最多可选300张</p>
            </div>
          </div>
          <div class="statusbar" style="display:none;">
            <div class="progress">
              <span class="text">0%</span> <span class="percentage"></span>
            </div>
            <div class="info"></div>
            <div class="btns">
              <div id="filepicker2"></div>
              <div class="uploadbtn">开始上传</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="row cl">
      <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-2">
        <button
          onclick="article_add('','invoicevo/save?&projectid=${projectid}&invoicescan=','10001');"
          class="btn btn-primary radius" type="button">
          <i class="hui-iconfont"></i>   保存  
        </button>
      </div>
    </div>
  </div>

   3、js代码

  1. <script type="text/javascript"
  2.   var imagepath=null
  3.     function article_save() { 
  4.       alert("刷新父级的时候会自动关闭弹层。"); 
  5.       window.parent.location.reload(); 
  6.     } 
  7.     /*项目发票-添加*/ 
  8.     function article_add(title, url, w, h) { 
  9.     if(imagepath){ 
  10.       var index = layer.open({ 
  11.         type : 2, 
  12.         title : title, 
  13.         content : url+imagepath 
  14.       }); 
  15.       layer.full(index); 
  16.     }else{alert("没有上传图片,请先上传图片");} 
  17.     } 
  18.     $(function() { 
  19.       $('.skin-minimal input').icheck({ 
  20.         checkboxclass : 'icheckbox-blue'
  21.         radioclass : 'iradio-blue'
  22.         increasearea : '20%' 
  23.       }); 
  24.       $list = $("#filelist"), $btn = $("#btn-star"), state = "pending"
  25.           uploader; 
  26.       var uploader = webuploader.create({ 
  27.         auto : true
  28.         swf : 'lib/webuploader/0.1.5/uploader.swf',// swf文件路径 
  29.         // 文件接收服务端。 
  30.         server : 'lib/webuploader/0.1.5/server/fileupload.php'// 文件接收服务端。 
  31.         // 选择文件的按钮。可选。 
  32.         // 内部根据当前运行是创建,可能是input元素,也可能是flash. 
  33.         pick : '#filepicker'
  34.         // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传! 
  35.         resize : false
  36.         // 只允许选择图片文件。 
  37.         accept : { 
  38.           title : 'images'
  39.           extensions : 'gif,jpg,jpeg,bmp,png'
  40.           mimetypes : 'image/*' 
  41.         } 
  42.       }); 
  43.       // 当有文件被添加进队列的时候 
  44.       uploader 
  45.           .on( 
  46.               'filequeued'
  47.               function(file) { 
  48.                 var $li = $('<div id="' + file.id + '" class="item">' 
  49.                     + '<div class="pic-box"><img></div>' 
  50.                     + '<div class="info">' 
  51.                     + file.name 
  52.                     + '</div>' 
  53.                     + '<p class="state">等待上传...</p>' 
  54.                     + '</div>'), $img = $li.find('img'); 
  55.                 $list.append($li); 
  56.                 // 创建缩略图 
  57.                 // 如果为非图片文件,可以不用调用此方法。 
  58.                 // thumbnailwidth x thumbnailheight 为 100 x 100 
  59.                 uploader.makethumb(file, function(error, src) { 
  60.                   if (error) { 
  61.                     $img.replacewith('<span>不能预览</span>'); 
  62.                     return
  63.                   } 
  64.                   $img.attr('src', src); 
  65.                 }, thumbnailwidth, thumbnailheight); 
  66.               }); 
  67.       // 文件上传过程中创建进度条实时显示。 
  68.       uploader 
  69.           .on( 
  70.               'uploadprogress'
  71.               function(file, percentage) { 
  72.                 var $li = $('#' + file.id), $percent = $li 
  73.                     .find('.progress-box .sr-only'); 
  74.                 // 避免重复创建 
  75.                 if (!$percent.length) { 
  76.                   $percent = $( 
  77.                       '<div class="progress-box"><span class="progress-bar radius"><span class="sr-only" style="width:0%"></span></span></div>'
  78.                       .appendto($li).find('.sr-only'); 
  79.                 } 
  80.                 $li.find(".state").text("上传中"); 
  81.                 $percent.css('width', percentage * 100 + '%'); 
  82.               }); 
  83.       // 文件上传成功,给item添加成功class, 用样式标记上传成功。 
  84.       uploader.on('uploadsuccess'function(file) { 
  85.         $('#' + file.id).addclass('upload-state-success'
  86.             .find(".state").text("已上传"); 
  87.       }); 
  88.       // 文件上传失败,显示上传出错。 
  89.       uploader.on('uploaderror'function(file) { 
  90.         $('#' + file.id).addclass('upload-state-error').find(".state"
  91.             .text("上传出错"); 
  92.       }); 
  93.       // 完成上传完了,成功或者失败,先删除进度条。 
  94.       uploader.on('uploadcomplete'function(file) { 
  95.         $('#' + file.id).find('.progress-box').fadeout(); 
  96.       }); 
  97.       uploader.on('all'function(type) { 
  98.         if (type === 'startupload') { 
  99.           state = 'uploading'
  100.         } else if (type === 'stopupload') { 
  101.           state = 'paused'
  102.         } else if (type === 'uploadfinished') { 
  103.           state = 'done'
  104.         } 
  105.         if (state === 'uploading') { 
  106.           $btn.text('暂停上传'); 
  107.         } else { 
  108.           $btn.text('开始上传'); 
  109.         } 
  110.       }); 
  111.       $btn.on('click'function() { 
  112.         if (state === 'uploading') { 
  113.           uploader.stop(); 
  114.         } else { 
  115.           uploader.upload(); 
  116.         } 
  117.       }); 
  118.     }); 
  119.     (function($) { 
  120.       // 当domready的时候开始初始化 
  121.       $(function() { 
  122.         var $wrap = $('.uploader-list-container'), 
  123.         // 图片容器 
  124.         $queue = $('<ul class="filelist"></ul>').appendto( 
  125.             $wrap.find('.queuelist')), 
  126.         // 状态栏,包括进度和控制按钮 
  127.         $statusbar = $wrap.find('.statusbar'), 
  128.         // 文件总体选择信息。 
  129.         $info = $statusbar.find('.info'), 
  130.         // 上传按钮 
  131.         $upload = $wrap.find('.uploadbtn'), 
  132.         // 没选择文件之前的内容。 
  133.         $placeholder = $wrap.find('.placeholder'), 
  134.         $progress = $statusbar.find('.progress').hide(), 
  135.         // 添加的文件数量 
  136.         filecount = 0, 
  137.         // 添加的文件总大小 
  138.         filesize = 0, 
  139.         // 优化retina, 在retina下这个值是2 
  140.         ratio = window.devicepixelratio || 1, 
  141.         // 缩略图大小 
  142.         thumbnailwidth = 110 * ratio, thumbnailheight = 110 * ratio, 
  143.         // 可能有pedding, ready, uploading, confirm, done. 
  144.         state = 'pedding'
  145.         // 所有文件的进度信息,key为file id 
  146.         percentages = {}, 
  147.         // 判断浏览器是否支持图片的base64 
  148.         issupportbase64 = (function() { 
  149.           var data = new image(); 
  150.           var support = true
  151.           data.onload = data.onerror = function() { 
  152.             if (this.width != 1 || this.height != 1) { 
  153.               support = false
  154.             } 
  155.           } 
  156.           data.src = "data:image/gif;base64,r0lgodlhaqabaiaaaaaaap///ywaaaaaaqabaaacauwaow=="
  157.           return support; 
  158.         })(), 
  159.         // 检测是否已经安装flash,检测flash的版本 
  160.         flashversion = (function() { 
  161.           var version; 
  162.           try { 
  163.             version = navigator.plugins['shockwave flash']; 
  164.             version = version.description; 
  165.           } catch (ex) { 
  166.             try { 
  167.               version = new activexobject( 
  168.                   'shockwaveflash.shockwaveflash'
  169.                   .getvariable('$version'); 
  170.             } catch (ex2) { 
  171.               version = '0.0'
  172.             } 
  173.           } 
  174.           version = version.match(/d+/g); 
  175.           return parsefloat(version[0] + '.' + version[1], 10); 
  176.         })(), 
  177.         supporttransition = (function() { 
  178.           var s = document.createelement('p').style, r = 'transition' in s 
  179.               || 'webkittransition' in s 
  180.               || 'moztransition' in s 
  181.               || 'mstransition' in s || 'otransition' in s; 
  182.           s = null
  183.           return r; 
  184.         })(), 
  185.         // webuploader实例 
  186.         uploader; 
  187.         if (!webuploader.uploader.support('flash'
  188.             && webuploader.browser.ie) { 
  189.           // flash 安装了但是版本过低。 
  190.           if (flashversion) { 
  191.             (function(container) { 
  192.               window['expressinstallcallback'] = function(state) { 
  193.                 switch (state) { 
  194.                 case 'download.cancelled'
  195.                   alert('您取消了更新!'
  196.                   break
  197.                 case 'download.failed'
  198.                   alert('安装失败'
  199.                   break
  200.                 default
  201.                   alert('安装已成功,请刷新!'); 
  202.                   break
  203.                 } 
  204.                 delete window['expressinstallcallback']; 
  205.               }; 
  206.               var swf = 'expressinstall.swf'
  207.               // insert flash object 
  208.               var html = '<object type="application/' 
  209.                   + 'x-shockwave-flash" data="' + swf + '" '
  210.               if (webuploader.browser.ie) { 
  211.                 html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '
  212.               } 
  213.               html += 'width="100%" height="100%" style="outline:0">' 
  214.                   + '<param name="movie" value="' + swf + '" />' 
  215.                   + '<param name="wmode" value="transparent" />' 
  216.                   + '<param name="allowscriptaccess" value="always" />' 
  217.                   + '</object>'
  218.               container.html(html); 
  219.             })($wrap); 
  220.             // 压根就没有安转。 
  221.           } else { 
  222.             $wrap 
  223.                 .html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_get_flash_player.jpg" /></a>'); 
  224.           } 
  225.           return
  226.         } else if (!webuploader.uploader.support()) { 
  227.           alert('web uploader 不支持您的浏览器!'); 
  228.           return
  229.         } 
  230.         // 实例化 
  231.         uploader = webuploader.create({ 
  232.           pick : { 
  233.             id : '#filepicker-2'
  234.             label : '点击选择图片' 
  235.           }, 
  236.           formdata : { 
  237.             uid : 123 
  238.           }, 
  239.           dnd : '#dndarea'
  240.           paste : '#uploader'
  241.           swf : 'lib/webuploader/0.1.5/uploader.swf'
  242.           chunked : false
  243.           chunksize : 512 * 1024, 
  244.           server : 'invoicevo/news_uploder?&projectid=${projectid}'
  245.           // runtimeorder: 'flash', 
  246.           // accept: { 
  247.           //   title: 'images', 
  248.           //   extensions: 'gif,jpg,jpeg,bmp,png', 
  249.           //   mimetypes: 'image/*' 
  250.           // }, 
  251.           // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。 
  252.           disableglobaldnd : true
  253.           filenumlimit : 300, 
  254.           filesizelimit : 200 * 1024 * 1024, // 200 m 
  255.           filesinglesizelimit : 50 * 1024 * 1024 
  256.         // 50 m 
  257.         }); 
  258.         // 拖拽时不接受 js, txt 文件。 
  259.         uploader.on('dndaccept'function(items) { 
  260.           var denied = false, len = items.length, i = 0, 
  261.           // 修改js类型 
  262.           unallowed = 'text/plain;application/javascript '
  263.           for (; i < len; i++) { 
  264.             // 如果在列表里面 
  265.             if (~unallowed.indexof(items[i].type)) { 
  266.               denied = true
  267.               break
  268.             } 
  269.           } 
  270.           return !denied; 
  271.         }); 
  272.         uploader.on('dialogopen'function() { 
  273.           console.log('here'); 
  274.         }); 
  275.         // uploader.on('filesqueued', function() { 
  276.         //   uploader.sort(function( a, b ) { 
  277.         //     if ( a.name < b.name ) 
  278.         //      return -1; 
  279.         //     if ( a.name > b.name ) 
  280.         //      return 1; 
  281.         //     return 0; 
  282.         //   }); 
  283.         // }); 
  284.         // 添加“添加文件”的按钮, 
  285. /*         uploader.addbutton({ 
  286.           id : '#filepicker2'
  287.           label : '继续添加' 
  288.         }); */ 
  289.         uploader.on('ready'function() { 
  290.           window.uploader = uploader; 
  291.         }); 
  292.         // 当有文件添加进来时执行,负责view的创建 
  293.         function addfile(file) { 
  294.           var $li = $('<li id="' + file.id + '">' 
  295.               + '<p class="title">' + file.name + '</p>' 
  296.               + '<p class="imgwrap"></p>' 
  297.               + '<p class="progress"><span></span></p>' + '</li>'), 
  298.           $btns = $( 
  299.               '<div class="file-panel">' 
  300.                   + '<span class="cancel">删除</span>' 
  301.                   + '<span class="rotateright">向右旋转</span>' 
  302.                   + '<span class="rotateleft">向左旋转</span></div>'
  303.               .appendto($li), $prgress = $li 
  304.               .find('p.progress span'), $wrap = $li 
  305.               .find('p.imgwrap'), $info = $('<p class="error"></p>'), 
  306.           showerror = function(code) { 
  307.             switch (code) { 
  308.             case 'exceed_size'
  309.               text = '文件大小超出'
  310.               break
  311.             case 'interrupt'
  312.               text = '上传暂停'
  313.               break
  314.             default
  315.               text = '上传失败,请重试'
  316.               break
  317.             } 
  318.             $info.text(text).appendto($li); 
  319.           }; 
  320.           if (file.getstatus() === 'invalid') { 
  321.             showerror(file.statustext); 
  322.           } else { 
  323.             // @todo lazyload 
  324.             $wrap.text('预览中'); 
  325.             uploader 
  326.                 .makethumb( 
  327.                     file, 
  328.                     function(error, src) { 
  329.                       var img; 
  330.                       if (error) { 
  331.                         $wrap.text('不能预览'); 
  332.                         return
  333.                       } 
  334.                       if (issupportbase64) { 
  335.                         img = $('<img src="'+src+'">'); 
  336.                         $wrap.empty().append(img); 
  337.                       } else { 
  338.                         $ 
  339.                             .ajax( 
  340.                                 'lib/webuploader/0.1.5/server/preview.php'
  341.                                 { 
  342.                                   method : 'post'
  343.                                   data : src, 
  344.                                   datatype : 'json' 
  345.                                 }) 
  346.                             .done( 
  347.                                 function
  348.                                     response) { 
  349.                                   if (response.result) { 
  350.                                     img = $('<img src="'+response.result+'">'); 
  351.                                     $wrap 
  352.                                         .empty() 
  353.                                         .append( 
  354.                                             img); 
  355.                                   } else { 
  356.                                     $wrap 
  357.                                         .text("预览出错"); 
  358.                                   } 
  359.                                 }); 
  360.                       } 
  361.                     }, thumbnailwidth, thumbnailheight); 
  362.             percentages[file.id] = [ file.size, 0 ]; 
  363.             file.rotation = 0; 
  364.           } 
  365.           file.on('statuschange'function(cur, prev) { 
  366.             if (prev === 'progress') { 
  367.               $prgress.hide().width(0); 
  368.             } else if (prev === 'queued') { 
  369.               $li.off('mouseenter mouseleave'); 
  370.               $btns.remove(); 
  371.             } 
  372.             // 成功 
  373.             if (cur === 'error' || cur === 'invalid') { 
  374.               console.log(file.statustext); 
  375.               showerror(file.statustext); 
  376.               percentages[file.id][1] = 1; 
  377.             } else if (cur === 'interrupt') { 
  378.               showerror('interrupt'); 
  379.             } else if (cur === 'queued') { 
  380.               percentages[file.id][1] = 0; 
  381.             } else if (cur === 'progress') { 
  382.               $info.remove(); 
  383.               $prgress.css('display''block'); 
  384.             } else if (cur === 'complete') { 
  385.               $li.append('<span class="success"></span>'); 
  386.             } 
  387.             $li.removeclass('state-' + prev).addclass( 
  388.                 'state-' + cur); 
  389.           }); 
  390.           $li.on('mouseenter'function() { 
  391.             $btns.stop().animate({ 
  392.               height : 30 
  393.             }); 
  394.           }); 
  395.           $li.on('mouseleave'function() { 
  396.             $btns.stop().animate({ 
  397.               height : 0 
  398.             }); 
  399.           }); 
  400.           $btns 
  401.               .on( 
  402.                   'click'
  403.                   'span'
  404.                   function() { 
  405.                     var index = $(this).index(), deg; 
  406.                     switch (index) { 
  407.                     case 0: 
  408.                       uploader.removefile(file); 
  409.                       return
  410.                     case 1: 
  411.                       file.rotation += 90; 
  412.                       break
  413.                     case 2: 
  414.                       file.rotation -= 90; 
  415.                       break
  416.                     } 
  417.                     if (supporttransition) { 
  418.                       deg = 'rotate(' + file.rotation 
  419.                           + 'deg)'
  420.                       $wrap.css({ 
  421.                         '-webkit-transform' : deg, 
  422.                         '-mos-transform' : deg, 
  423.                         '-o-transform' : deg, 
  424.                         'transform' : deg 
  425.                       }); 
  426.                     } else { 
  427.                       $wrap 
  428.                           .css( 
  429.                               'filter'
  430.                               'progid:dximagetransform.microsoft.basicimage(rotation=' 
  431.                                   + (~~((file.rotation / 90) % 4 + 4) % 4) 
  432.                                   + ')'); 
  433.                     } 
  434.                   }); 
  435.           $li.appendto($queue); 
  436.         } 
  437.         // 负责view的销毁 
  438.         function removefile(file) { 
  439.           var $li = $('#' + file.id); 
  440.           delete percentages[file.id]; 
  441.           updatetotalprogress(); 
  442.           $li.off().find('.file-panel').off().end().remove(); 
  443.         } 
  444.         function updatetotalprogress() { 
  445.           var loaded = 0, total = 0, spans = $progress.children(), percent; 
  446.           $.each(percentages, function(k, v) { 
  447.             total += v[0]; 
  448.             loaded += v[0] * v[1]; 
  449.           }); 
  450.           percent = total ? loaded / total : 0; 
  451.           spans.eq(0).text(math.round(percent * 100) + '%'); 
  452.           spans.eq(1).css('width', math.round(percent * 100) + '%'); 
  453.           updatestatus(); 
  454.         } 
  455.         function updatestatus() { 
  456.           var text = '', stats; 
  457.           if (state === 'ready') { 
  458.             text = '选中' + filecount + '张图片,共' 
  459.                 + webuploader.formatsize(filesize) + '。'
  460.           } else if (state === 'confirm') { 
  461.             stats = uploader.getstats(); 
  462.             if (stats.uploadfailnum) { 
  463.               text = '已成功上传' 
  464.                   + stats.successnum 
  465.                   + '张照片至xx相册,' 
  466.                   + stats.uploadfailnum 
  467.                   + '张照片上传失败,<a class="retry" href="#" rel="external nofollow" rel="external nofollow" >重新上传</a>失败图片或<a class="ignore" href="#" rel="external nofollow" rel="external nofollow" >忽略</a>' 
  468.             } 
  469.           } else { 
  470.             stats = uploader.getstats(); 
  471.             text = '共' + filecount + '张(' 
  472.                 + webuploader.formatsize(filesize) + '),已上传' 
  473.                 + stats.successnum + '张'
  474.             if (stats.uploadfailnum) { 
  475.               text += ',失败' + stats.uploadfailnum + '张'
  476.             } 
  477.           } 
  478.           $info.html(text); 
  479.         } 
  480.         function setstate(val) { 
  481.           var file, stats; 
  482.           if (val === state) { 
  483.             return
  484.           } 
  485.           $upload.removeclass('state-' + state); 
  486.           $upload.addclass('state-' + val); 
  487.           state = val; 
  488.           switch (state) { 
  489.           case 'pedding'
  490.             $placeholder.removeclass('element-invisible'); 
  491.             $queue.hide(); 
  492.             $statusbar.addclass('element-invisible'); 
  493.             uploader.refresh(); 
  494.             break
  495.           case 'ready'
  496.             $placeholder.addclass('element-invisible'); 
  497.             $('#filepicker2').removeclass('element-invisible'); 
  498.             $queue.show(); 
  499.             $statusbar.removeclass('element-invisible'); 
  500.             uploader.refresh(); 
  501.             break
  502.           case 'uploading'
  503.             $('#filepicker2').addclass('element-invisible'); 
  504.             $progress.show(); 
  505.             $upload.text('暂停上传'); 
  506.             break
  507.           case 'paused'
  508.             $progress.show(); 
  509.             $upload.text('继续上传'); 
  510.             break
  511.           case 'confirm'
  512.             $progress.hide(); 
  513.             $('#filepicker2').removeclass('element-invisible'); 
  514.             $upload.text('开始上传'); 
  515.             stats = uploader.getstats(); 
  516.             if (stats.successnum && !stats.uploadfailnum) { 
  517.               setstate('finish'); 
  518.               return
  519.             } 
  520.             break
  521.           case 'finish'
  522.             stats = uploader.getstats(); 
  523.             if (stats.successnum) { 
  524.               alert('上传成功'); 
  525.             } else { 
  526.               // 没有成功的图片,重设 
  527.               state = 'done'
  528.               location.reload(); 
  529.             } 
  530.             break
  531.           } 
  532.           updatestatus(); 
  533.         } 
  534.         uploader.onuploadprogress = function(file, percentage) { 
  535.           var $li = $('#' + file.id), $percent = $li 
  536.               .find('.progress span'); 
  537.           $percent.css('width', percentage * 100 + '%'); 
  538.           percentages[file.id][1] = percentage; 
  539.           updatetotalprogress(); 
  540.         }; 
  541.         uploader.onfilequeued = function(file) { 
  542.           filecount++; 
  543.           filesize += file.size; 
  544.           if (filecount === 1) { 
  545.             $placeholder.addclass('element-invisible'); 
  546.             $statusbar.show(); 
  547.           } 
  548.           addfile(file); 
  549.           setstate('ready'); 
  550.           updatetotalprogress(); 
  551.         }; 
  552.         uploader.onfiledequeued = function(file) { 
  553.           filecount--; 
  554.           filesize -= file.size; 
  555.           if (!filecount) { 
  556.             setstate('pedding'); 
  557.           } 
  558.           removefile(file); 
  559.           updatetotalprogress(); 
  560.         }; 
  561.         /*获取服务器返回的数据*/ 
  562.         uploader.on('uploadsuccess'function(file, response) { 
  563.           alert(response.status); 
  564.           if (response.status == "success") { 
  565.             imagepath =response.filepath; 
  566.             alert("文件保存路径:" + response.filepath); 
  567.           } else if (response.status == "error"
  568.             alert(response.error); 
  569.         }); 
  570.         uploader.on('all'function(type) { 
  571.           var stats; 
  572.           //alert(type); 
  573.           switch (type) { 
  574.           case 'uploadfinished'
  575.             setstate('confirm'); 
  576.             break
  577.           case 'startupload'
  578.             setstate('uploading'); 
  579.             break
  580.           case 'stopupload'
  581.             setstate('paused'); 
  582.             break
  583.           } 
  584.         }); 
  585.         uploader.onerror = function(code) { 
  586.           alert('eroor: ' + code); 
  587.         }; 
  588.         $upload.on('click'function() { 
  589.           if ($(this).hasclass('disabled')) { 
  590.             return false
  591.           } 
  592.           if (state === 'ready') { //点击上传按钮,进入准备状态。 
  593.             uploader.upload(); //开始上传 
  594.           } else if (state === 'paused') { 
  595.             uploader.upload(); 
  596.           } else if (state === 'uploading') { 
  597.             uploader.stop(); 
  598.           } 
  599.         }); 
  600.         $info.on('click''.retry'function() { 
  601.           uploader.retry(); 
  602.         }); 
  603.         $info.on('click''.ignore'function() { 
  604.           alert('todo'); 
  605.         }); 
  606.         $upload.addclass('state-' + state); 
  607.         updatetotalprogress(); 
  608.       }); 
  609.     })(jquery); 
  610.   </script> 

     注意:

webuploader 实现图片批量上传功能附实例代码

webuploader 实现图片批量上传功能附实例代码

webuploader 实现图片批量上传功能附实例代码

4、controller代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/**
   * 跳转到上传发票的页面
   * @param proname
   * @param map
   * @return
   */
  @requestmapping(value = "/upload" )
  public string invoiceupload(string proname,long id,map<string, object> map){
    map.put("proname", proname);
    projectservice.getproject(id);
    map.put("projectid", id);
    return "project/invoiceupload";
  }
  /**
   * 上传发票并保存导数据库
   * @param file
   * @param request
   * @param response
   * @return
   */
  @responsebody
  @requestmapping(value = "/news_uploder", method ={requestmethod.post,requestmethod.get}, produces = "application/json; charset=utf-8")  
  public jsonobject uploder(@requestparam multipartfile[] file,long projectid,httpservletrequest request,httpservletresponse response){
    string flag=null;
    jsonobject jsonobject = new jsonobject();
    try {
      webuploaderutil webuploaderutil=new webuploaderutil();
      webuploaderutil.upload(file[0], "upload/invoice/", request);
      flag=webuploaderutil.getfilename();
      jsonobject.put("filepath", flag);
      jsonobject.put("status", "success");
    } catch (exception e) {
      e.printstacktrace();
    }  
    return jsonobject;
  }
  5、工具类
  package com.softjx.util;
/**
 *project name: qdlimap
 *file name:  webuploaderutil.java
 *package name: com.ltmap.platform.cms.util
 *date:     2017年4月13日 下午6:30:45
 *copyright (c) 2017,578888218@qq.com all rights reserved.
*/
import java.io.file;
import java.text.simpledateformat;
import java.util.date;
import javax.servlet.http.httpservletrequest;
import org.springframework.web.multipart.multipartfile;
/**
 *title:   webuploaderutil<br/>
 *description:
 *@company:  励图高科<br/>
 *@author:  刘云生
 *@version:  v1.0
 *@since:   jdk 1.8.0_40
 *@date:   2017年4月13日 下午6:30:45 <br/>
*/
public class webuploaderutil {
  private string allowsuffix = "jpg,png,gif,jpeg";//允许文件格式
  private long allowsize = 2l;//允许文件大小
  private string filename;
  private string[] filenames;
  public string getallowsuffix() {
    return allowsuffix;
  }
  public void setallowsuffix(string allowsuffix) {
    this.allowsuffix = allowsuffix;
  }
  public long getallowsize() {
    return allowsize*1024*1024;
  }
  public void setallowsize(long allowsize) {
    this.allowsize = allowsize;
  }
  public string getfilename() {
    return filename;
  }
  public void setfilename(string filename) {
    this.filename = filename;
  }
  public string[] getfilenames() {
    return filenames;
  }
  public void setfilenames(string[] filenames) {
    this.filenames = filenames;
  }
  /**
   
   * @title:    getfilenamenew 
   * @description: todo 
   * @param:    @return
   * @return:   string
   * @author:   刘云生
   * @date:    2017年4月14日 上午10:17:35  
   * @throws
   */
  private string getfilenamenew(){
    simpledateformat fmt = new simpledateformat("yyyymmddhhmmsssss");
    return fmt.format(new date());
  }
  /**
   
   * @title:    uploads 
   * @description: todo 
   * @param:    @param files
   * @param:    @param destdir
   * @param:    @param request
   * @param:    @throws exception
   * @return:   void
   * @author:   刘云生
   * @date:    2017年4月14日 上午10:17:14  
   * @throws
   */
  public void uploads(multipartfile[] files, string destdir,httpservletrequest request) throws exception {
    string path = request.getcontextpath();
    string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path;
    try {
      filenames = new string[files.length];
      int index = 0;
      for (multipartfile file : files) {
        string suffix = file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof(".")+1);
        int length = getallowsuffix().indexof(suffix);
        if(length == -1){
          throw new exception("请上传允许格式的文件");
        }
        if(file.getsize() > getallowsize()){
          throw new exception("您上传的文件大小已经超出范围");
        }
        string realpath = request.getsession().getservletcontext().getrealpath("/");
        file destfile = new file(realpath+destdir);
        if(!destfile.exists()){
          destfile.mkdirs();
        }
        string filenamenew = getfilenamenew()+"."+suffix;//
        file f = new file(destfile.getabsolutefile()+"\"+filenamenew);
        file.transferto(f);
        f.createnewfile();
        filenames[index++] =basepath+destdir+filenamenew;
      }
    } catch (exception e) {
      throw e;
    }
  }
  /**
   
   * @title:    upload 
   * @description: todo 
   * @param:    @param file
   * @param:    @param destdir
   * @param:    @param request
   * @param:    @throws exception
   * @return:   void
   * @author:   刘云生
   * @date:    2017年4月14日 上午10:16:16  
   * @throws
   */
  public void upload(multipartfile file, string destdir,httpservletrequest request) throws exception {
    string path = request.getcontextpath();
    //http://localhost:8088/huahang
    string basepath = request.getscheme()+"://"+request.getservername()+":"+request.getserverport()+path;
    try {
        string suffix = file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof(".")+1);
        int length = getallowsuffix().indexof(suffix);
        if(length == -1){
          throw new exception("请上传允许格式的文件");
        }
        if(file.getsize() > getallowsize()){
          throw new exception("您上传的文件大小已经超出范围");
        }
        string realpath = request.getsession().getservletcontext().getrealpath("/")+"/";
        file destfile = new file(realpath+destdir);
        if(!destfile.exists()){
          destfile.mkdirs();
        }
        string filenamenew = getfilenamenew()+"."+suffix;
        file f = new file(destfile.getabsolutefile()+"/"+filenamenew);
        file.transferto(f);
        f.createnewfile();
        //包含网站的全路径http://localhost:8080/qdlimap/upload/user/20170414104142667.png
        //filename = basepath+destdir+filenamenew;
        //返回相对路径upload/user/20170414104142667.png
        filename = destdir+filenamenew;
    } catch (exception e) {
      throw e;
  }
}
}

总结

以上所述是小编给大家介绍的webuploader 实现图片批量上传功能附实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.cnblogs.com/HawkFalcon/archive/2017/11/30/7727028.html

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部