1. 程式人生 > >webuploader 百度上傳元件

webuploader 百度上傳元件

webuploader api 文件 http://fex.baidu.com/webuploader/doc/

在我們的專案中新增上傳圖片功能

原始頁面如下



我們在原有的jsp上加上下面程式碼

(1)引入百度上傳js css
<link rel="stylesheet" type="text/css"
    href="<%=basePath%>/plug-in/webuploader/js/webuploader.css">
    <script type="text/javascript"

        src="<%=basePath%>/plug-in/webuploader/js/webuploader.js"></script>

(2)呼叫百度上傳元件

<script>

   var $ = jQuery, $list = $('#thelist'), state = 'pending', uploader;
          jQuery(function() {
                //判斷是否是新增 若新增 這個id為空 若不是新增那麼該人已經在系統存在 表示這個人已經上傳過簽名了 就顯示他以前的簽名照片
                var s=$("#id").val();
                if(s==null||s==""||s==undefined){
                }else{
                  $("#filelists").removeAttr("style");
                }
                

                uploader = WebUploader.create({
                    // swf檔案路徑
                    swf : '${webRoot}/plug-in/webuploader/js/Uploader.swf',
                    // 檔案接收服務端。
                    server : 'uploadDataController.do?uploadQMPic',
                    // 不壓縮image
                    resize : false,
                    //weifasle手動上傳 true 選擇就上傳
                    auto:false,
                    //是否允許在檔案傳輸時提前把下一個檔案準備好。 對於一個檔案的準備工作比較耗時,比如圖片壓縮,md5序列化。 如果能提前在當前檔案傳輸期處理,可以節省總體耗時
                    prepareNextFile:false,
                    // 內部根據當前執行是建立,可能是input元素,也可能是flash.
                    pick : '#picker',
                    //是否要分片處理大檔案上傳。
                    chunked : false,
                    //多大分片chunkSize : 1014 * 1024,
                    //併發上傳
                    threads : true,
                    // formData {Object} [可選] [預設值:{}]檔案上傳請求的引數表,每次傳送都會發送此物件中的引數。
                    //驗證檔案總數量, 超出則不允許加入佇列。
                    fileNumLimit : 10,
                    //驗證單個檔案大小是否超出限制, 超出則不允許加入佇列。
                    fileSingleSizeLimit : 1000 * 1024 * 1024,
                    //去重 根據檔名字、檔案大小和最後修改時間來生成hash Key.
                    duplicate : true,
                    //指定接受哪些型別的檔案。 由於目前還有ext轉mimeType表,所以這裡需要分開指定。
                    accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } ,
                    thumb:{
                            width: 77,
                            height: 29,

                            // 圖片質量,只有type為`image/jpeg`的時候才有效。
                            quality: 70,

                            // 是否允許放大,如果想要生成小圖的時候不失真,此選項應該設定為false.
                            allowMagnify:false,

                            // 是否允許裁剪。
                            crop: true,

                            // 為空的話則保留原有圖片格式。
                            // 否則強制轉換成指定的型別。
                            type: 'image/jpeg'
                    }
            
                    
                });

                // 當有檔案新增進來的時候
                uploader.on('fileQueued', function(file) {
                     var card = $("#idcard").val();
                       //alert(card);
                       if(card==null||card==""||card==undefined) {
                          $("#isfzjy").html("請先填寫身份證號碼");
                          $("#isfzjy").css("color","red");
                          $("#idcard").focus;
                          return false;
                       }
                
                   document.getElementById("picker").style.display='none';
                   document.getElementById("quxiao").style.display='block';
                   //刪除原有的div
                    $("#pic").attr("style","display:none");
                    var $li = $( '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>' ), $img = $li.find('img');
                    // $list為容器jQuery例項
                    $("#thelist").append( $li );
                    // 建立縮圖 // 如果為非圖片檔案,可以不用呼叫此方法。 // thumbnailWidth x thumbnailHeight 為 100 x 100
                    uploader.makeThumb( file, function( error, src ) {
                        if ( error ) { $img.replaceWith('<span>不能預覽</span>');
                        return;
                        }
                    //設定剛剛選著的照片的大小
                    $img.attr( 'src', src ); }, 77, 29 );
                    //alert($li);
                 
                   //$("#picker").css("display","none");
                   //上傳檔案列表顯示
                  // $("#filelists").css("display","block");
                   $("#filelists").removeAttr("style");
                   //$("#fileurl").removeAttr("style");
                
                   
                  uploader.options.formData.picName = card;
                   uploader.upload();
                });
                
                
                // 檔案上傳過程中建立進度條實時顯示。
                uploader.on(
                                'uploadProgress',
                                function(file, percentage) {
                                    var $li = $('#' + file.id), $percent = $li.find('.progress .progress-bar');
                                  
                                    // 避免重複建立
                                    if (!$percent.length) {
                                        $percent = $(
                                                '<div class="progress progress-striped active">'
                                                        + '<div class="progress-bar" role="progressbar" style="width: 0%">'
                                                        + '</div>' + '</div>')
                                                .appendTo($li)
                                                .find('.progress-bar');
                                    }

                                    $li.find('p.state').text('上傳中');

                                    $("#progress_span").html((percentage*100).toFixed(2)+'%');
                                    //$percent.css('width', percentage * 100 + '%');
                                });
                uploader.on('uploadSuccess', function(file, response) {
                    if(0==response.success){
                      //alert(1);
                       $('#' + file.id).find('p.state').text('已上傳');
                       setFileInfo(response.obj);
                    }else{
                        $('#' + file.id).find('p.state').text('上傳失敗!');
                    }    
                });
                uploader.on('uploadError', function(file, reason) {
                    //$('#' + file.id).find('p.state').text('上傳出錯');
                     swal('上傳出錯!');
                     document.location.reload();//當前頁面  
                });
                uploader.on('uploadComplete', function(file) {
                    $('#' + file.id).find('.progress').fadeOut();
                });
                uploader.on('all', function(type) {
                    if (type === 'startUpload') {
                        state = 'uploading';
                    } else if (type === 'stopUpload') {
                        state = 'paused';
                    } else if (type === 'uploadFinished') {
                        state = 'done';
                    }
                });
                uploader.upload();
            });

        //上傳成功回撥 吧上傳的圖片地址 寫到我們的jsp上,表單提交時候取這個div的值儲存到表中

          function setFileInfo(data){
               //alert(data.filePath);
                  $("#picurl").val(data.filePath);
          }

//點選取消 時候 把剛剛上傳的檔案刪掉

          function quxiao(){
              document.getElementById("picker").style.display='block';
              document.getElementById("quxiao").style.display='none';
              var s=$("#id").val();
              if(s==null||s==""||s==undefined){
                 //新建病人
                  $("#filelists").attr("style","display:none");
                  //獲取剛剛上傳的照片的絕對路徑
                  var picurl=$("#picurl").val();
                  var bz=1;//新建病人時候刪出身份證圖片
                  $("#thelist").empty();
                  
                  //ajax 請求後臺 刪除上傳檔案
                   $.ajax({
                            type: "POST",                                         
                            url: "uploadDataController.do?delIdcardPic",           
                            dataType: "json",                                  
                            data: { url: picurl,bz: bz},      
                            success: function (data) {

                                //刪出成功 把picurl值刪出
                                $("#picurl").val("");                
                                }
                             
                        });
                 
              }else{
              //修改病人
              //原圖片顯示
              $("#pic").removeAttr("style");
               //新增圖片隱藏
                $("#thelist").empty();
                var bz=2;
                var picurl=$("#picurl").val();
                 $.ajax({
                            type: "POST",                                         
                            url: "uploadDataController.do?delIdcardPic",           
                            dataType: "json",                                  
                            data: { url: picurl,bz: bz},      
                            success: function (data) {

                                //刪出成功 把picurl值刪出
                                //$("#picurl").val("");                
                                }
                             
                        });
              }
              
              
              
          }

</script>

jsp 新增程式碼

<tr>
                <td align="right" height="60px"><label class="Validform_label"> <t:mutiLang langKey="簽名照片"/>: </label></td>
                <td class="value" >
                    <div id ="picker">選擇檔案</div>
                    <div id ="quxiao"  onclick="quxiao()" style="width:83px;height:34px; background-color:#00b7ee; border-radius:3px; color:#ffffff; text-align:center; padding-top:10px; display:none;">取消選擇</div>
                    
                </td>
            </tr>
            
            <tr id="filelists" style="display:none">
                <td align="right" ><label class="Validform_label"> <t:mutiLang langKey="簽名照片瀏覽"/>: </label></td>
                <td class="value">
                    

                     <div id="thelist" class="uploader-list"> </div>

                         <!--用來存放我們圖片的 ,當不是新增,是編輯時候,要顯示圖片-->

                      <div id="pic"><img src="data:image/png;base64,${imgPath}" width="77" height="29" /></div>  
                      
                </td>
            </tr>
            
            <tr id="fileurl"  style="display:none" >
                <td align="right" ><label class="Validform_label"> <t:mutiLang langKey="簽名照片路徑"/>: </label> </td>
                <td class="value">
                     <!--用來存放圖片路徑 -->
                     <div>
                        <input id="picurl" class="inputxt" name="picurl" value="${user.signatureFile}"/>
                     </div>
                </td>
            </tr>

在form表單提交時候

//判斷是不是真增

var s=$("#id").val();
            var bz=3;
            var picurl=$("#picurl").val();
            if(s!=null&&s!=""&&s!=undefined){
                  //刪除身份證資料夾中back的
                  $.ajax({
                        type: "POST",                                         
                        url: "uploadDataController.do?delIdcardPic",           
                        dataType: "json",                                  
                        data: { url: picurl,bz: bz},      
                        success: function (data) {              
                            }
                         
                    });
           
            };

java程式碼

@SuppressWarnings("unchecked")
    @RequestMapping(params = "uploadQMPic", method = { RequestMethod.POST,RequestMethod.GET })
    public void uploadQMPic(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        File targetFile = null;
        String msg = null;
        int code = 0;
        try {

            //找到檔案儲存路徑 ,根據實際情況定義

             String realPath = FileGenerater.getPathUpload("qianming_pic");
            
              if(request.getParameter("chunk") == null) {
                    String fileName = System.currentTimeMillis()+"_"+file.getOriginalFilename();//存在硬碟上的檔名
                    if(fileName.length()>32){//修改文防止名字過長
                        fileName = fileName.substring(0,fileName.length());
                    }
                    targetFile = new File(realPath, fileName);//存在
                    file.transferTo(targetFile); // 小檔案,直接拷貝
                }else{
                    int chunk = Integer.parseInt(request.getParameter("chunk")); // 當前分片
                    int chunks = Integer.parseInt(request.getParameter("chunks")); // 分片總計

                    String Ogfilename = file.getOriginalFilename();
                    targetFile = new File(realPath, Ogfilename);
                    OutputStream outputStream = new FileOutputStream(targetFile, true);
                    InputStream inputStream = file.getInputStream();

                    byte buffer[] = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, len);
                    }
                    inputStream.close();
                    outputStream.close();
               }
               if(FileCheckUtil.isDanger(targetFile)){
                    throw new Exception("非法檔案!");
                }
            //操作成功  
            Map map = new HashMap();
            code = 0;
            msg = "success!";
            map.put("filePath", targetFile.getAbsolutePath());
            map.put("fileName", targetFile.getName());
            map.put("fileLength", targetFile.length());
            ResponseUtil.flushJson(response, new JsonRe(code,msg, map));
                
        }catch(Exception e){
            //操作失敗
            e.printStackTrace();
            msg = e.getMessage();
            ResponseUtil.flushJson(response, new JsonRe(1,msg, null));
        }
   }

/**
     * 刪除上傳的圖片
     * @param request
     * @param response
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(params = "delIdcardPic", method = { RequestMethod.POST,RequestMethod.GET })
    public void delIdcardPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url=request.getParameter("url");
        String bz=request.getParameter("bz");
        if(bz.equals("1")){
            if(url!=null){
                File f= new File(url);
                if(f.exists()){
                    f.delete();
                }
            }
        }else if(bz.equals("2")){
            if(url!=null){
                File f= new File(url);
                if(f.exists()){
                    f.delete();
                    //String newurl=url.substring(0,url.indexOf("_back"));
                    String newurl=url+"_back";
                    System.out.println(newurl);
                    File  newf= new File(newurl);
                    if(newf.exists()){
                        newf.renameTo(new File(url));
                    }
                }
                    
            }
            
        }else{
            if(url!=null){
                url=url+"_back";
                File f=new File(url);
                if(f.exists()){
                    f.delete();
                }
            }
        }
    }

上面儲存完上傳的圖片,並且把路徑儲存到相應的表中了,現在我們就要實現編輯使用者時候,這個圖要顯示出來在上面的jsp程式碼裡,

<div id="pic"><img src="data:image/png;base64,${imgPath}" width="77" height="29" /></div>

我實現的思路是 ,通過表裡儲存的路徑 ,拿到2進位制資料,轉base64,傳到前臺。

java程式碼

 if(user.getSignatureFile()!=null&&!user.getSignatureFile().equals("")){
            File f = new File(user.getSignatureFile());
            FileInputStream input;
            try {
                input = new FileInputStream(f);
                byte[] buffer = new byte[(int) f.length()];
                input.read(buffer);
                input.close();
                //System.out.println(Base64.byteArrayToBase64(buffer));
                req.setAttribute("imgPath", Base64.byteArrayToBase64(buffer));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            
        }