webuploader的一個頁面多個上傳按鈕實例


借鑒一位大佬的demo  附上他的github地址https://github.com/lishuqi

我把他的cxuploader.js改了不需要預覽  直接上傳圖片后拿到回傳地址給img標簽顯示圖片

 

 

    jQuery(function() {

        uploader = new Array();//創建 uploader數組
        // 優化retina, 在retina下這個值是2
        var ratio = window.devicePixelRatio || 1,
        // 縮略圖大小
        thumbnailWidth = 100 * ratio,
        thumbnailHeight = 100 * ratio,
        supportTransition = (function(){
            var s = document.createElement('p').style,
            r = 'transition' in s ||
                  'WebkitTransition' in s ||
                  'MozTransition' in s ||
                  'msTransition' in s ||
                  'OTransition' in s;
            s = null;
            return r;
        })();
         // 所有文件的進度信息,key為file id
        var percentages = {};
        var state = 'pedding';
        
        //可行性判斷
        if ( !WebUploader.Uploader.support() ) {
            alert( 'Web Uploader 不支持您的瀏覽器!如果你使用的是IE瀏覽器,請嘗試升級 flash 播放器');
            throw new Error( 'WebUploader does not support the browser you are using.' );
        }
        
        //循環頁面中每個上傳域
        $('.uploder-container').each(function(index){
            
            // 添加的文件數量
            var fileCount = 0;
            // 添加的文件總大小
            var fileSize = 0;
            
            var filePicker=$(this).find('.filePicker');//上傳按鈕實例
            var queueList=$(this).find('.queueList');//拖拽容器實例
            var placeholder=$(this).find('.placeholder');//按鈕與虛線框實例
            var statusBar=$(this).find('.statusBar');//再次添加按鈕容器實例
            var info =statusBar.find('.info');//提示信息容器實例
            // 圖片容器           
            var queue = $('<ul class="filelist"></ul>').appendTo( queueList);
            var filePickerid = $(this).find('.filePicker').id;
            
            
            //初始化上傳實例
            uploader[index] = WebUploader.create({
                pick: {
                    id:filePicker,
                    class:filePicker,
                    label: '上傳'
                 
                },
                dnd: queueList,
               
                //這里可以根據 index 或者其他,使用變量形式
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png,doc',
                    mimeTypes: 'image/*'
                },

                // swf文件路徑
                swf: 'js/Uploader.swf',

                disableGlobalDnd: true,//禁用瀏覽器的拖拽功能,否則圖片會被瀏覽器打開

                chunked: false,//是否分片處理大文件的上傳
                            
                server: 'fileUpload.do',//上傳地址
                
                fileNumLimit: 1,//一次最多上傳文件個數
                
                fileSizeLimit: 10 * 1024 * 1024,    // 總共的最大限制10M
                
                fileSingleSizeLimit: 3 * 1024 * 1024 ,   // 單文件的最大限制3M
                auto :true,
                
                formData: {                
                    token:index//可以在這里附加控件編號,從而區分是哪個控件上傳的
                    
                }
            });
            
     
            uploader[index].on('uploadSuccess',function(file,response){
                 alert(JSON.stringify(response));
                 console.log("file:",file);
                 console.log("response:",response);
                 console.log("fileAdress:",response.fileAdress);
                 var imageid = "#"+response.imageAddr+"_1";
                    mini.get(response.imageAddr).setValue(response.fileAdress);
                    placeholder.hide();
                    queueList.hide();
                 //document.getElementById(response.imageAddr).value=response.fileAdress;
                 $(imageid).attr("src",response.fileAdress);
                alert("上傳成功");
            });
            

            //可以在這里附加額外上傳數據
            
            uploader[index].on('uploadBeforeSend',function(object,data,header) {
                
                //alert("id:"+filePicker.attr("id"));
                //獲得當前id的長度
                var divlen = filePicker.attr("id").length;
                //alert("divlen"+divlen);
                //截取id的值后兩位不要
                var imageAddr = filePicker.attr("id").substring(0, divlen-2); 
            var genre=$(":input[name='genre']").val();
              data=$.extend(data,{
               genre:genre,
               imageAddr:imageAddr
               });    
           data.formData= {genre:genre,imageAddr:imageAddr};
          
            });
        });
        
    });
    
 
    
    

 

刪除圖片只是隱藏div,不能刪服務器
<script type="text/javascript">
/*刪除圖片  */
function deleteImage(path) {
    //圖片名稱
    var imageAddrs = mini.get(path).getValue();
    alert(path);
    alert(imageAddrs);
    
    mini.get(path).setValue("");
    $("#"+path+"_1").attr("src"," ");
    $("#"+path+"_5").hide();
    document.getElementById(path + "_4").style.display = '';
    document.getElementById(path + "_3").style.display = '';
    /* 
    硬刪除
    if (imageAddrs == ""|| imageAddrs== null|| imageAddrs == undefined) {
        alert("照片為空,請重新操作");
    }else{
        
        $.ajax({
            type : "POST",
            url : "ajax/removeImage",
            data : {
                imageAddr : imageAddrs
            },
            dataType : "json",
            // 下面三個參數要指定,如果不指定,會報一個JQuery的錯誤 
            success : function(data) {
                console.log(data);
                console.log(data.mess);
                alert(data.mess);
                alert(imageAddrs);
                // 刪除成功后刷新頁面
                $(".cxuploder").html(page);
                 window.location.reload();
            }
        });
    } */
}
</script>

上傳控制層

 

    // 允許上傳圖片的格式
    private static final String[] IMAGE_TYPE = { ".jpg", ".jpge", ".bmp", ".png", "gif" };
    
    /**
     *圖片上傳
     * 
     * @param id
     * @param name
     * @param flog
     * @param autoId
     * @param size
     * @param type
     * @param file
     * @param request
     */
    @RequestMapping(value = "fileUpload.do",method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(String genre,String imageAddr,@RequestParam("file")MultipartFile file,HttpServletRequest request,HttpServletResponse response){
       
        Map<String,Object> resultMap=new HashMap <String, Object>();

        Boolean flag = false;
         System.out.println(file.getOriginalFilename());
        //校驗圖片格式
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                flag = true;
                break;
            }
        }
        //如果圖片校驗錯誤,直接返回。
        if (!flag) {
            return "";
        }
        
         //獲取當前時間 File.separator等同於/或者\\

        String fileFolder = File.separator + DateUtil.getYear(new Date())
        + File.separator +  DateUtil.getMonth(new Date()) + File.separator
        + DateUtil.getDay(new Date());
        try {
            //設置根目錄
            //設置根目錄
            /*String filePathGen = request.getSession().getServletContext()
                    .getRealPath("/") + "upload/photoPhoto/images/";
            String uploadPath ="";*/
             String uploadPath="";//圖片上傳的目錄
             InputStream in = this.getClass().getResourceAsStream("/conf.properties");
              Properties props = new Properties();
              InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
              props.load(inputStreamReader);
              if("renyuan".equals(genre)) {
                  uploadPath = props.getProperty("Upload_path")+genre+fileFolder;
              }else if ("cheliang".equals(genre)) {
                  uploadPath =props.getProperty("Upload_path")+genre+fileFolder;
            }
              
              
              
              
                 System.out.println(file.getOriginalFilename());
               
              //生成圖片的絕對路徑
              //重新命名
                String  newFileName= "";
                String fileName = file.getOriginalFilename();
                  if(null!=fileName){
                      newFileName=UUID.randomUUID ()+fileName.substring (fileName.lastIndexOf ("."));
                  }
                //創建File對象
                File newfile = new File(uploadPath+File.separator+newFileName);
                //如果文件目錄不存在,則進行創建
                if (!newfile.isDirectory()) {
                    newfile.mkdirs();
                }
                //把圖片寫入到磁盤中
                try {
                    file.transferTo(newfile);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
        
            
             resultMap.put("fileAdress","/upload"+File.separator+genre+fileFolder+File.separator+newFileName);
              resultMap.put("imageAddr",imageAddr);
              resultMap.put("uploadFlag",true);
             //獲取照片類型  人員/車輛
         
            System.out.println(genre);
            System.out.println(imageAddr);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("uploadFlag",false);
        }
          String json=JSONObject.toJSONString(resultMap).toString();
          writeJson(json,response);    

        return null;
    }

    /*
     * 寫入數據
     */
    private void writeJson(String json, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(json);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                out.close();
            }
        }
  }

 

上面的是上傳圖片的控制層,點擊上傳圖片立馬上傳

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM