1. 程式人生 > >webuploader+springmvc實現多檔案上傳(html+js+css原創,後臺程式碼借鑑)

webuploader+springmvc實現多檔案上傳(html+js+css原創,後臺程式碼借鑑)

———————-css—————————-

/*新增圖片按鈕*/
.add_resume_item {
  cursor: pointer;
}
/*遮罩層*/
.zpzs_gray {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: gray;
  opacity: 0.6;
  filter: alpha(opacity=60);
  display: none;
  z-index: 100;
}
/*彈出框*/
#uploader {
  display: none;
  height
: 414px
; width: 830px; position: fixed; margin-top: -207px; margin-left: -415px; top: 50%; left: 50%; background-color: #fff; border: 1px solid #ddd; z-index: 101; }
/*彈出框頭部*/ #uploader .add_img_head { height: 44px; font-size: 12px; background-color: #ff8400; position: relative; color
: #fff
; }
#uploader .add_img_head span { background: url("../images/imgHead_grzp.png") 0 0 no-repeat; position: absolute; display: block; top: 12px; left: 5px; width: 180px; height: 20px; } #uploader .add_img_head b { background: url("../images/closeImg.png") 0 0 no-repeat; position: absolute
; display: block; top: 0; right: 0; width: 32px; height: 21px; cursor: pointer; }
/*選擇圖片按鈕*/ #uploader .add_img { height: 150px; width: 300px; position: absolute; margin-top: -75px; margin-left: -150px; top: 50%; left: 50%; } #uploader .add_img p { text-align: center; color: #999; font-size: 14px; } #uploader .add_img .uploadBtn { display: none; position: absolute; right: 10px; width: 118px; height: 38px; line-height: 38px; top: 8px; cursor: pointer; text-align: center; color: #fff; background: url("../images/uploaderbtn.png") 0 0 no-repeat; } #uploader .add_img #filePicker { height: 38px; width: 128px; text-align: center; color: #fff; line-height: 38px; margin-left: 86px; position: relative; margin-bottom: 20px; background: url("../images/chooseImg_grzp.png") 0 0 no-repeat; } #uploader .add_img #filePicker div { width: 100% !important; height: 100% !important; position: absolute; top: 0; left: 0; opacity: 0; filter: alpha(opacity=0); } #uploader .add_img #filePicker div.webuploader-pick { opacity: 1; filter: alpha(opacity=100); color: #fff; } #uploader .add_img #filePicker input, #uploader .add_img #filePicker label{ width: 100% !important; height: 100% !important; position: absolute; top: 0; left: 0; } #uploader #fileList { padding-left: 20px; } /*單個縮圖容器*/ #uploader .file-item { float: left; width: 118px; overflow: hidden; border: 1px solid #969696; height: 128px; line-height: 128px; text-align: center; margin-left: 10px; margin-top: 10px; position: relative; } #uploader .file-item img { width: 100%; vertical-align: middle; } #uploader .file-item .info { position: absolute; width: 100%; height: 28px; bottom: 0; left: 0; background-color: #ddd; cursor: pointer; line-height: 28px; } #uploader .file-item p.progress { position: absolute; width: 100%; bottom: 0; left: 0; height: 18px; overflow: hidden; z-index: 50; margin: 0; border-radius: 0; background: #e8e8e8; -webkit-box-shadow: 0 0 0; } #uploader .file-item p.progress span { display: block; overflow: hidden; width: 0; height: 100%; background: #f4b887; -webit-transition: width 200ms linear; -moz-transition: width 200ms linear; -o-transition: width 200ms linear; -ms-transition: width 200ms linear; transition: width 200ms linear; -webkit-animation: progressmove 2s linear infinite; -moz-animation: progressmove 2s linear infinite; -o-animation: progressmove 2s linear infinite; -ms-animation: progressmove 2s linear infinite; animation: progressmove 2s linear infinite; -webkit-transform: translateZ(0); }

———————-js—————————-
1.自行下載webuploader.js

jQuery(function () {
  var $ = jQuery,
  //彈出上傳框
    $wrap = $('#uploader'),
  //圖片縮圖容器
    $list = $('#fileList'),
  //開始上傳按鈕
    $upload = $wrap.find('.uploadBtn'),
  //縮圖壓縮程度
    ratio = window.devicePixelRatio || 1,
  //縮圖大小
    thumbnailWidth = 100 * ratio,
    thumbnailHeight = 100 * ratio,
  //Web Uploader例項
    uploader;
  //初始化Web Uploader
  uploader = WebUploader.create({
    //自動上傳。
    auto: false,
    //swf檔案路徑
    swf: basePath + 'picture/Uploader.swf',
    //檔案接收服務端。
    server: basePath + 'uploadPicture',
    //選擇檔案的按鈕。
    pick: '#filePicker',
    //單次上傳最多圖片數
    fileNumLimit: 12,
    //單個檔案最大為2m
    fileSingleSizeLimit: 2*1024*1024,
    //允許選擇的圖片格式
    accept: {
      title: 'Images',
      extensions: 'gif,jpg,jpeg,bmp,png',
      mimeTypes: 'image/*'
    }
  });

   // 當有檔案新增進來的時候
  uploader.on('fileQueued', function (file) {
    //圖片數目限制為12張
    if ($('.file-item').length < 12) {
      //建立新新增圖片和刪除條
      var $li = $(
          '<div id="' + file.id + '" class="file-item">' +
          '<img>' +
          '<div class="info">刪除</div>' +
          '</div>'
        ),
        $info = $li.find('.info'),
        $img = $li.find('img');
      //將新新增圖片放入縮圖容器
      $list.append($li);
      //為圖片刪除條新增單擊刪除事件
      $info.on('click', function () {
        //將圖片移除上傳序列
        uploader.removeFile(file, true);
        //將圖片從縮圖容器刪除
        var $li = $('#' + file.id);
        $li.off().remove();
        $('#filePicker').children().css('display','');
        if ($('#filePicker').attr('class') === 'qyfc_upload webuploader-container') {
          $('#filePicker').css('background', 'url("images/chooseImg_qyfc.png") 0 0 no-repeat');
        } else {
          $('#filePicker').css('background', 'url("images/chooseImg_grzp.png") 0 0 no-repeat');
        }
      });
      // 建立縮圖
      uploader.makeThumb(file, function (error, src) {
        if (error) {
          $img.replaceWith('<span>不能預覽</span>');
          return;
        }
        $img.attr('src', src);
      }, thumbnailWidth, thumbnailHeight);
      //新增圖片完成後將新增按鈕和上傳按鈕固定在彈出框底部
      $('.add_img').css({
        'left': '0',
        'top': '350px',
        'width': '100%',
        'margin-top': '0',
        'margin-left': '0',
        'height': '60px',
        'padding-top': '8px'
      });
      //為彈出框內元素更改樣式和新增事件
      $('.uploadBtn').css({'display': 'block'});
      $('#filePicker').css({'margin-left': '540px'});
      $('.add_img p').css({'display': 'none'});
      if ($('.file-item').length >= 12) {
        $('#filePicker').children().css('display', 'none');
        if ($('#filePicker').attr('class') === 'qyfc_upload webuploader-container') {
          $('#filePicker').css('background', 'url("images/chooseImg_qyfcdis.png") 0 0 no-repeat');
        } else {
          $('#filePicker').css('background', 'url("images/chooseImg_grzpdis.png") 0 0 no-repeat');
        }
      }
    }
  });

  // 檔案上傳過程中建立進度條實時顯示。
  uploader.on('uploadProgress', function (file, percentage) {
    var $li = $('#' + file.id),
      $percent = $li.find('.progress span'),
      $info = $li.find('.info');
    // 避免重複建立
    if (!$percent.length) {
      $percent = $('<p class="progress"><span></span></p>')
        .appendTo($li).find('span');
    }
    $info.css({display: 'none'});
    $percent.css('width', percentage * 100 + '%');
  });

  // 檔案上傳成功,給info新增文字,標記上傳成功。
  uploader.on('uploadSuccess', function (file) {
    var $li = $('#' + file.id), $info = $li.find('.info');
    $li.off();
    $info.off().text('上傳成功!')
      .css({color: 'green', display: 'block'});
  });

  // 檔案上傳失敗,給info新增文字,標記上傳失敗。
  uploader.on('uploadError', function (file) {
    var $li = $('#' + file.id),
      $info = $li.find('.info');
    $info.off().text('上傳失敗!')
      .css({color: 'red', display: 'block'});
  });

  // 上傳成功或失敗後刪除進度條。
  uploader.on('uploadComplete', function (file) {
    $('#' + file.id).find('.progress').remove();
  });

  //單擊開始上傳按鈕開始上傳
  $upload.on('click', function () {
    if ($('#fileList').children().length) {
      $('.uploadBtn').css('background', 'url("images/uploaderbtndis.png") 0 0 no-repeat');
      if ($('#filePicker').attr('class') === 'qyfc_upload webuploader-container') {
        $('#filePicker').css('background', 'url("images/chooseImg_qyfcdis.png") 0 0 no-repeat');
      } else {
        $('#filePicker').css('background', 'url("images/chooseImg_grzpdis.png") 0 0 no-repeat');
      }
      $('#filePicker').children().css('display', 'none');
      timer = setInterval(function () {
        if ($upload.html() === '重新上傳' || $upload.html() === '開始上傳' || $upload.html() === '上傳中...') {
          $upload.html('上傳中')
        } else {
          $upload.html($upload.html() + '.')
        }
      }, 500);
      $('.info').html('等待上傳..').off();
      if ($upload.html() === '重新上傳') {
        uploader.retry();
      } else {
        uploader.upload();
      }
    }
  });

  //全部上傳完成時觸發關閉彈出層
  uploader.on('uploadFinished', function () {
    $('.uploadBtn').css('background', 'url("images/uploaderbtn.png") 0 0 no-repeat');
    clearInterval(timer);
    closeBtn();
  });

  //單擊頁面上的上傳圖片選項彈出上傳框
  $('.add_resume_item').click(function () {
    $('.zpzs_gray,#uploader').css('display', 'block');
  });

  //單擊上傳框上叉號按鈕新增關閉上傳框
  $('.closeBtn').click(closeBtn);

  //關閉彈出窗
  function closeBtn() {
    //獲取上傳出錯和未上傳的圖片
    var allPic = $('#fileList').children().length,
      inited = uploader.getFiles('inited').length,
      error = uploader.getFiles('error').length,
      queued = uploader.getFiles('queued').length;
    //判斷是否可以關閉視窗
    if (error) {
      $upload.html('重新上傳');
      if (window.confirm('您已上傳成功' + (allPic - error) + '張,上傳失敗' + error + '張,可能由於網路原因上傳失敗,是否確認關閉視窗!')) {
        closeuploader();
      }
    } else if (inited) {
      $upload.html('開始上傳');
      if ($('#filePicker').attr('class') === 'qyfc_upload webuploader-container') {
        var text = '企業風采';
      } else {
        var text = '個人作品';
      }
      if (window.confirm('您還有'+text+'尚未上傳!\r\r是否確認取消上傳?')) {
        closeuploader();
      }
    } else if (queued) {
      if (window.confirm('您還有' + text + '等待上傳!\r\r是否確認關閉視窗!')) {
        closeuploader();
      }
    } else {
      if (allPic) {
        window.location.href = window.location.href;
      }
      closeuploader();
    }
    //關閉上傳框視窗後恢復上傳框初始狀態
    function closeuploader() {
      //關閉上傳框
      $('.zpzs_gray,#uploader').css('display', 'none');
      //移除所有縮圖並將圖片移除上傳序列
      for (var i = 0; i < uploader.getFiles().length; i++) {
        //將圖片從上傳序列移除
        uploader.removeFile(uploader.getFiles()[i], true);
        delete uploader.getFiles()[i];
        //將圖片從縮圖容器移除
        var $li = $('#' + uploader.getFiles()[i].id);
        $li.off().remove();
      }
      //恢復上傳框內元素樣式
      $('#filePicker,.uploadBtn,.add_img p,.add_img').removeAttr("style");
      if ($('#filePicker').attr('class') === 'qyfc_upload webuploader-container') {
        $('#filePicker').css('background', 'url("images/chooseImg_qyfc.png") 0 0 no-repeat');
      } else {
        $('#filePicker').css('background', 'url("images/chooseImg_grzp.png") 0 0 no-repeat');
      }
      $('#filePicker').children().removeAttr("style");
      $upload.html('開始上傳');
    }
  }
});
/**
 * 顯示檔案上傳彈層
 * @return
 */
function showUploadFrame(){
    $('.zpzs_gray,#uploader').css('display', 'block');
}

———————html———————————————-

<!--彈出遮罩層-->
        <div class="zpzs_gray"></div>
        <!--上傳框開始-->
        <div id="uploader">
          <!--上傳框頭部-->
          <div class="add_img_head">
            <span></span>
            <b class="closeBtn"></b>
          </div>
          <!--縮圖容器-->
          <div id="fileList"></div>
          <!--選擇圖片按鈕-->
          <div class="add_img">
            <div id="filePicker"></div>
            <p>按住Ctrl可多選照片</p>

            <p>單次上傳最多12張(單張最大2M)</p>

            <div class="uploadBtn">開始上傳</div>
          </div>
        </div>
        <!--上傳框結束-->
        <script src="<%=basePath %>js/jobSoo/startSet1.js"></script>

—————————-後臺程式碼———————————————————-

Controller層

@RequestMapping("uploadPicture")
@ResponseBody
public void uploads(@RequestParam("file")MultipartFile[] files, String destDir,
        HttpServletRequest request,HttpServletResponse response) {
    try {
        userUploadPictureService.uploads(files, destDir, request,response);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Service層

public void uploads(MultipartFile[] files, String destDir,
            HttpServletRequest request,HttpServletResponse response) throws Exception {
        User user = (User)request.getSession().getAttribute("user");
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + 
            request.getServerPort() + path;
        // 獲取檔案上傳的真實路徑
        String uploadPath = request.getSession().getServletContext().getRealPath("/");
        List<String> picPaths = new ArrayList<String>();
        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("請上傳允許格式的檔案");
                }
                destDir = "staticResource/user/picture/" + user.getId();
                File destFile = new File(uploadPath + destDir);
                if (!destFile.exists()) {
                    destFile.mkdirs();
                }
                String fileNameNew = getFileNameNew() + "." + suffix;//
                File f = new File(destFile.getAbsoluteFile() + File.separator + fileNameNew);
                //如果當前檔案已經存在了,就跳過。
                if(f.exists()){
                    continue;
                }
                file.transferTo(f);
                f.createNewFile();
                fileNames[index++] = basePath + destDir + fileNameNew;
            }
            //個人作品展示
            if(user.getUserType() == 0){
                Resume resume = resumeDao.findResumeByUserId(user.getId());
                String resumeRank = resume.getResumeRank();
                //若不存在,新增上“作品展示”,並更新
                if(resumeRank.indexOf(":zpzs") == -1){
                    resumeRank = resumeRank+":zpzs";
                    resume.setResumeRank(resumeRank);
                    resumeDao.updateResume(resume);
                }
                request.getSession().setAttribute("user", user);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 為檔案重新命名,命名規則為當前系統時間毫秒數
     * @return string
     */
    private String getFileNameNew() {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return fmt.format(new Date());
    }