1. 程式人生 > >嵌入layui元件實現圖片與附件上傳

嵌入layui元件實現圖片與附件上傳

通過layui元件實現上傳附件業務

jsp嵌入layui上傳附件元件

<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/platform/views/cusviews/devMatainView/js/layui/css/layui.css"> 
<script type="text/javascript" src="<%=request.getContextPath() %>/platform/views/cusviews/devMatainView/js/layui/layui.js" charset="utf-8"></script>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<input id="root" type="hidden" value="${ctx }"/>
<input id="ids" type="hidden" value="<%=request.getParameter("ids") %>"/>

    <!-- 檔案上傳 開始 --> 
              <div class="layui-form-item layui-form-text">
                  <div class="layui-input-block">
                   <button type="button" class="layui-btn" id="fileAttachment">
                <i class="layui-icon">&#xe67c;</i>上傳檔案
             </button>
             <div class="layui-upload" id="fileAttachment_list">
                <div class="layui-upload-list">
                  <table class="layui-table" id="tableid">
                    <thead>
                      <tr><th width="13%">縮圖</th>
                      <th width="25%">檔名</th>
                      <th width="30%">檔案路徑</th>
                      <th width="17%">上傳時間</th>
                      <th width="15%">操作</th>
                    </tr></thead>
                    <tbody id="fileAttachment_list_table"></tbody>
                  </table>
                </div>  
             </div> 
                  </div>
               </div>
      <!-- 檔案預覽 開始 -->
      <div class="layui-upload" id="fileAttachment_preview" style="display:none;">
          <div class="layui-upload-list">
            <table class="layui-table">
              <thead>
                <tr><th>檔名</th>
                <th>大小</th>
                <th>狀態</th>
                <th>操作</th>
              </tr></thead>
              <tbody id="fileAttachment_Preview_Table"></tbody>
            </table>
          </div>
        <button type="button" class="layui-btn" id="fileAttachment_Action">開始上傳</button>
      </div>
<!-- 檔案上傳 結束 -->
  <div class="btn">
        <a id="save">儲存</a>
        <a id="reset">重置</a>
  </div>
  
  <input type="hidden"  id="afvFileId" name="afvFileId"/>
  <input type="hidden"  id="fileAtIds" name="fileAtIds"/>


<script type="text/javascript">
var fileRoot = $("#root").val();
layui.use('upload', function(){
    var upload = layui.upload;
    var that = this;
  //多檔案列表示例
    var demoListView = $('#fileAttachment_Preview_Table')
    ,uploadListIns = upload.render({
      elem: '#fileAttachment'
      ,url: fileRoot+'/file/upload'
      ,accept: 'file'
      ,multiple: true
      ,data: {
          'tableName':"RECODR_MAINTAIN_VOLTAGE",
        'fieldName':"FILEATTACHMENT",
        'pkFieldName':"RECORD_VOLTAGE_ID",
        'entityId':function(){
            return $("#afvFileId").val();
        },
        isDelete:0
        }
      ,auto: false
      ,bindAction: '#fileAttachment_Action'
      ,choose: function(res){ 
        if ($("#afvFileId").val() == "") {
          alert("請先儲存基礎資訊之後才能上傳圖片");
          return false;
        }
        var layIndex = layer.open({
            type: 1,
            title: "預覽",
            maxmin: false,
            area : ['40%', '40%'],
            content:$("#fileAttachment_preview").removeAttr('style'),      //$.loadHtml(preUrl),
            success: function(layero){
              var demoListView = $("#fileAttachment_Preview_Table").empty();
              var files = that.files = res.pushFile(); //將每次選擇的檔案追加到檔案佇列
                  //讀取本地檔案
              res.preview(function(index, file, result){
                    var tr = $(['<tr id="upload-'+ index +'">'
                      ,'<td>'+ file.name +'</td>'
                      ,'<td>'+ (file.size/1024).toFixed(1) +' kb</td>'
                      ,'<td name="upload-status">等待上傳</td>'
                      ,'<td>'
                        ,'<button class="layui-btn layui-btn-mini demo-reload layui-hide">重傳</button>'
                        ,'<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">刪除</button>'
                      ,'</td>'
                    ,'</tr>'].join(''));
                    
                    //單個重傳
                    tr.find('.demo-reload').live('click', function(){
                      res.upload(index, file);
                    });
                    
                    //刪除
                    tr.find('.demo-delete').live('click', function(){
                      
                      delete files[index]; //刪除對應的檔案
                      tr.remove();
                      uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免刪除後出現同名檔案不可選
                      if(Object.getOwnPropertyNames(files).length == 0){      //當上傳預覽沒有檔案時,關閉彈出框
                         layer.close(layIndex);
                      }
                    });
                    demoListView.append(tr);
                  });
            },
            end : function(){  //layer銷燬回撥
              $("#fileAttachment_preview").attr('style','display:none;');
              $("#fileAttachment_Preview_Table").empty();
            },
            cancel: function(){       //右上角關閉回撥
            }
          });
      }
      ,done: function(res, index, upload){
        if(res.retStatus == 1){ //上傳成功
          var tr = demoListView.find('tr#upload-'+ index)
          ,tds = tr.children();
          tds.eq(2).html('<span style="color: #5FB878;">上傳成功</span>');
          tds.eq(3).html(''); //清空操作
          delete that.files[index]; //刪除檔案佇列已經上傳成功的檔案 */
          var afvFileId = $("#afvFileId").val();
          readFile(afvFileId);
        }  
      }
      ,error: function(index, upload){
        var tr = demoListView.find('tr#upload-'+ index)
        ,tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上傳失敗</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //顯示重傳
      }
    });
 });

/*  渲染附件 */
function readFile(afvFileId){
	debugger;
 var demoListView = $('#fileAttachment_Preview_Table');
 $.ajax({
     type:"post",
     dataType: "json", 
     data : {"id":afvFileId},
     url:fileRoot+"/getFileAttachment",
     success:function(msg){
    	 debugger;
       if(msg&&msg.length>0){
         $("#tableid tbody").html("");
         //處理卡片頁面列表展示問題
         for (var i = 0;i<msg.length;i++) {
           var afile = msg[i].data;
           var imageUrl = fileRoot+'/file?id='+afile.ATTACHMENTID;
            var html = '<img src='+imageUrl+' max-width="120" width="120" height="80" style="cursor:pointer;"/></td>';
            
            var $tr = $(['<tr id="upload-'+ afile.ATTACHMENTID +'" attatchmentId="'+ afile.ATTACHMENTID +'">'
                  ,'<td>' + html
                  ,'<td>'+ afile.ATTACHMENTNAME +'</td>'
                  ,'<td>'+ afile.FILEPATH +'</td>'
                  ,'<td>'+ afile.CREATEDATE +'</td>'
                  ,'<td>'
                    ,'<a class="layui-btn layui-btn-mini demo-reload" href="'+fileRoot+'/file/fileDown?id='+afile.ATTACHMENTID+'">下載</a>&nbsp;&nbsp;'
                    ,'<button class="layui-btn layui-btn-mini layui-btn-danger" id="delButton">刪除</button>'
                  ,'</td>'
                ,'</tr>'].join(''));
            debugger;
            $tr.find('button').bind('click',function(){
            debugger;
                var attId = "";
                $(this).closest("tr").remove();
                $("#fileAttachment_list_table tr").each(function(index,item){
                  attId += $(item).attr("attatchmentid")+",";
                });
                attId = attId.substr(0, attId.length - 1);  
                var afvFileId = $("#afvFileId").val();
              var url = fileRoot+"/removeFileAttachment",params={"mainId":afvFileId,"attId":attId};
              $.ajax({
                type : "post",
                url : url,
                async : false,
                data : params,
                success : function(data){
                  /* $("#uploadAttachmentIds").data("uploadAttachmentIds").removeByValue(attId); */
                  return;
                }
              });
              });
              $("#fileAttachment_list_table").append($tr);
         }
       }
     }
   })
}
</script>

js

var root = null;
var ids = null;

$(document).ready(function() {
	root = $("#root").val();
	ids = $("#ids").val();
	initpage();
});

function initpage(){
	root = $("#root").val();

	if(null!=ids&&ids.length>0){
		readAfv();
		readFile(ids);
	}
	var timer = "";
	$("#save").click(function(){
		/*儲存之前,要先把資料庫中FILEATTACHMENT查出來,然後一併儲存*/
		var fileAtIds = "";
		if(null!=ids&&ids.length>0){
			param = {"ids":ids}
		    $.ajax({  
		        url:root + "/beforeSavePic",  
		        data:param,  
		        type:"post",  
		        dataType:"json",
		        async: false,
		        success:function(data){ 
		        	debugger;
		        	fileAtIds = data;
		        	$("input[name='fileAtIds']").val(fileAtIds);
		            
		        },  
		        error:function(){  
		        	alert("伺服器正忙,請稍後重試");  
		        }  
		    }) 
		}else{
			var afvFId = $("input[name='afvFileId']").val();
			if(null!=afvFId&&afvFId.length>0){
				param = {"ids":afvFId}
				  $.ajax({  
				        url:root + "/beforeSavePic",  
				        data:param,  
				        type:"post",  
				        dataType:"json",
				        async: false,
				        success:function(data){ 
				        	fileAtIds = data;
				        	$("input[name='fileAtIds']").val(fileAtIds);
				            
				        },  
				        error:function(){  
				        	alert("伺服器正忙,請稍後重試");  
				        }  
				}) 
			}

		}
		afvSave(fileAtIds);
		$(this).attr("disabled", true); 
		timer = setTimeout(function(){
			debugger;
			$("#save").attr("disabled", false); 
		},20000);
	})
	
}

function afvSave(fileAtIds){
	var fileAtIds=$("input[name='fileAtIds']").val();
	param = {"fileAtIds":fileAtIds}
    $.ajax({  
        url:root + "/AddAfv",  
        data:param,  
        type:"post",  
        dataType:"json",  
        success:function(data){ 
        	/*儲存之後,要把主鍵的值拿回來*/
        	$("input[name='afvFileId']").val(data);
        	$("input[id='ids']").val(data);
            alert("儲存成功");  
        },  
        error:function(){  
        	alert("伺服器正忙,請稍後重試");  
        }  
    }) 

  }


function readAfv(){
	var param = {"ids" : ids};
	var uxl = root + "/queryAfv";
	$.ajax({
     type : "POST",
     url : uxl,
     data : param,
     success : function(list) {
     	$.each(list,function(index,obj){
     		var afvFileId = obj.data.RECORD_VOLTAGE_ID;
     		$("input[name='afvFileId']").val(afvFileId);
     	});
     },
     error : function(data) {
          
     },
 });
	return true;	
}

後臺

@Controller
public class AddVoltageAfv {
	@SuppressWarnings("unchecked")
	@RequestMapping("/AddAfv")
	@ResponseBody
	public String Addxctyz(HttpServletRequest request, HttpServletResponse response) {
		String fileAtIds = request.getParameter("fileAtIds");
		JSONObject jsonObject = JSON.parseObject(requestParam);

		String addIds = "";
		if (null != ids && ids.length() > 0) {
			String delSql1 = "delete from RECODR_MAINTAIN_VOLTAGE where RECORD_VOLTAGE_ID=?";
			Object paramd1 = ids;
			SqlUtil.getExecutor().execute(delSql1.toString(), paramd1);
			
			 String sqlSearch ="select decode(max(RECORD_VOLTAGE_ID),null,0,max(RECORD_VOLTAGE_ID)+1) RECORD_VOLTAGE_ID from RECODR_MAINTAIN_VOLTAGE";
			 IBean queryOne = SqlUtil.getExecutor().queryOne(sqlSearch);
			  addIds = queryOne.get("RECORD_VOLTAGE_ID", "");
			
			Object[] params = { addIds,orandid, volType,fileAtIds};
			String sql = "insert into RECODR_MAINTAIN_VOLTAGE(RECORD_VOLTAGE_ID,RECORD_VOLTAGE_DATE,DEVICEASSOC_ID,VOLTAGE_TYPE,FILEATTACHMENT) VALUES(?,(select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual),?,?,?)";
			SqlUtil.getExecutor().execute(sql.toString(), params);

		} else {
			 String sqlSearch ="select decode(max(RECORD_VOLTAGE_ID),null,0,max(RECORD_VOLTAGE_ID)+1) RECORD_VOLTAGE_ID from RECODR_MAINTAIN_VOLTAGE";
			 IBean queryOne = SqlUtil.getExecutor().queryOne(sqlSearch);
			  addIds = queryOne.get("RECORD_VOLTAGE_ID", "");
			
			Object[] params = { addIds,orandid, volType,fileAtIds};
			String sql = "insert into RECODR_MAINTAIN_VOLTAGE(RECORD_VOLTAGE_ID,RECORD_VOLTAGE_DATE,DEVICEASSOC_ID,VOLTAGE_TYPE,FILEATTACHMENT) VALUES(?,(select to_char(sysdate, 'yyyy-mm-dd hh24:mi:ss') from dual),?,?,?)";
			SqlUtil.getExecutor().execute(sql.toString(), params);

		}
		return addIds;
	}

@RequestMapping("/getFileAttachment")
	@ResponseBody
	public List<?> getFileAttachment(HttpServletRequest request, HttpServletResponse response) {
		 String str = request.getParameter("id");
		 String sql ="select t.fileattachment from recodr_maintain_voltage t where t.record_voltage_id ="+str;
		 IBean queryOne = SqlUtil.getExecutor().queryOne(sql);
		 String attachmentIds = queryOne.get("FILEATTACHMENT", "");
		 String[] strs = attachmentIds.split(",");
		 List<IBean> retList = new ArrayList<IBean>();
		 for(String id:strs){
			 String sqlids = "select a.* from BDC_ATTACHMENT a where a.attachmentid ="+id;
			 IBean queryAttach = SqlUtil.getExecutor().queryOne(sqlids);
			 retList.add(queryAttach);
		 }
		 return retList;
	}
	
	
	@RequestMapping("/beforeSavePic")
	@ResponseBody
	public String beforeSavePic(HttpServletRequest request, HttpServletResponse response) {
		 String str = request.getParameter("ids");
		 String sql ="select t.fileattachment from recodr_maintain_voltage t where t.record_voltage_id ="+str;
		 IBean queryOne = SqlUtil.getExecutor().queryOne(sql);
		 String attachmentIds = queryOne.get("FILEATTACHMENT", "");
		 return attachmentIds;
	}
	
	
	@RequestMapping("/removeFileAttachment")
	@ResponseBody
	public Boolean removeFileAttachment(HttpServletRequest request){
		String mainId = request.getParameter("mainId");
		String attId = request.getParameter("attId");
		String sql = "update RECODR_MAINTAIN_VOLTAGE set FILEATTACHMENT = ? where RECORD_VOLTAGE_ID =?";
		Object[] params ={attId,mainId};
		 boolean ztlist= SqlUtil.getExecutor().execute(sql, params);
		 if(ztlist){
			 return true;
		 }else{
			 return false;
		 }
	}