layui使用記錄


一、layui表格渲染

  如果后台返回的實力類里面包含另一個實體類,那么需要使用如下方式取出相應的值

var tableResult = table.render({
        elem: '#' + Server.tableId,
        url: Feng.ctxPath + '/server/page',
        page: true,
        height: "full-158",
        cellMinWidth: 100,
        cols: Server.initColumn()
    });

/**
     * 初始化表格的列  這里需要使用templet自定義
     */
    Server.initColumn = function () {
        return [[
            {type: 'checkbox'},
                    {field: 'id', sort: true, title: '編號'},
                    {field: 'projectId',hide:true, sort: true, title: '項目id'},
                    {field: 'project', sort: true, title: '所屬項目',templet: function(data){
                        return data.project.projectName;
                    }},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 200}
        ]];
    };

 

二、layui動態渲染select

  如果需要顯示默認的請選擇需要在原始的select標簽里面添加一個value=“” 的option  同時改option可以使select的 lay-verify="required" 必填屬性生效

1.html部分

<select id="projectId" lay-verify="required" lay-filter="projectId" lay-search>
        <option value="">請選擇</option>
</select>

2.js部分

//加載項目
	$.ajax({
		type: 'POST',
		url: Feng.ctxPath + "/problem/loadProject",
		async:false,
		success: function(res) {
     		var result  = res;
     		if(null != result && ""!=result){
				for(var i = 0; i < result.length; i++) {
					$('#projectId').append(new Option(result[i].projectName, result[i].id));
					
				}
			}
		}
	});
//動態加載后需要重新渲染
form.render();

  

三、layui文件上傳

1.html

<button type="button" class="layui-btn" id="upload">
	<i class="layui-icon"></i>上傳文件/圖片
</button>

2.js     

  layui 的多文件上傳是不斷的調用上傳方法直至所有文件上傳完畢

          var i=0;//上傳成功個數
          var fileIdStr = "";//用來記錄每次上傳 之后方法的返回值

		

          upload.render({ elem: this, url: Feng.ctxPath + '/form/form_view/upload', method: 'POST',//調用方式 accept: 'file', size: 51200,//上傳文件大小限制(KB)實際使用過程中未生效 auto: true,//是否選中后自動上傳 multiple: true,//是否允許多文件上傳 drag: true,//是否允許拖拽上傳 number: 5,//上傳數量限制 實際使用過程中未生效 before: function(obj) { //obj參數包含的信息,跟 choose回調完全一致,可參見上文。 layer.load(); //上傳loading
                   //這里的data可以添加上傳時額外的參數 //this.data={'storeId': storeId,'storeName':storeName}; }, choose: function(obj) { var files = this.files = obj.pushFile(); //將每次選擇的文件追加到文件隊列 obj.preview(function(index, file, result){ console.log("index"+index); //得到文件索引 console.log(file); //得到文件對象 console.log(result); //得到文件base64編碼,比如圖片 }); }, done: function(res, index, upload) { if(res.code == 0) { //上傳成功 i++; fileIdStr += res.fileId + ","; } //this.error(index, upload); //layer.closeAll('loading'); //關閉loading }, allDone: function(obj){ //當文件全部被提交后,才觸發   console.log(obj.total); //得到總文件數   console.log(obj.successful); //請求成功的文件數   console.log(obj.aborted); //請求失敗的文件數   if(obj.total==i){ fileIdStr = fileIdStr.substr(0,fileIdStr.length-1); $("input[name = '"+that.id+"']").val(fileIdStr); layer.closeAll('loading'); Feng.success("全部上傳成功!"); i = 0; fileIdStr = "";   }   }, error: function(index, upload) { Feng.error("上傳失敗!"); layer.closeAll('loading'); //關閉loading } });

3.java

 @BussinessLog(value = "上傳文件")
    @RequestMapping("/form_view/upload")
    @ResponseBody
    public Map<String,Object> upload( HttpServletRequest request) throws Exception{
        Map<String,Object> resultMap=new HashMap<String, Object>();//返回值
        Map<String,Object> Map=new HashMap<String, Object>();//與resultMap一起組成標准的layui上傳文件返回參數

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;//獲取前台傳來的數據
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();//文件集合

        //上傳文件路徑  該路徑與工具上傳路徑 獲取方式相同均在項目啟動設置文件中進行設置
        String path=finalDirPath+"/upload";
        // 檢查目錄
        File uploadDir = new File(path);
        if (!uploadDir.isDirectory()) {
            // 如果不存在,創建文件夾
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
        }

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {//循環文件集合
            SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
            String date=df2.format(new Date());
            MultipartFile file=entity.getValue();
            String filename=file.getOriginalFilename();

            File filepath=new File(path,filename);
            //判斷路徑是否存在,如果不存在就創建一個
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
            //重命名文件並保存
            //原名
            String fileStart =  filename.substring(0,filename.lastIndexOf("."));
            // 擴展名
            String fileExt = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();//擴展名
            Date date2=df2.parse(date);
            //新的文件名
            String newFileName=fileStart+"_"+date+"_"+new Random().nextInt(100)+"."+fileExt;
            //將文件信息保存至 數據庫
            SysFileInfo sysFileInfo = new SysFileInfo();
            sysFileInfo.setFileData(path+"/"+newFileName);

            sysFileInfoService.save(sysFileInfo);

            //將上傳的文件保存到目標文件中
            file.transferTo(new File(path+File.separator+newFileName));
        //標准的layui返回格式
            resultMap.put("code",0);
            resultMap.put("msg","success");
            resultMap.put("fileId",sysFileInfo.getFileId());
            Map.put("src",path);
            resultMap.put("data",Map);
        }
        return resultMap;
    }

  

  

  

 


免責聲明!

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



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