注:轉載請署名javascript
1、實體css
package com.ebd.application.modules.fileManage.pojo; public class FilesOrDirs { private String id; private String permission; private String owner; private String group; private String type; private String size; private String modificationTime; private String name; private String dirs; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPermission() { return permission; } public void setPermission(String permission) { this.permission = permission; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getGroup() { return group; } public void setGroup(String group) { this.group = group; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getModificationTime() { return modificationTime; } public void setModificationTime(String modificationTime) { this.modificationTime = modificationTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDirs() { return dirs; } public void setDirs(String dirs) { this.dirs = dirs; } }
2、前端頁面html
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta http-equiv="Access-Control-Allow-Origin" content="*"> <meta name="renderer" content="webkit"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="format-detection" content="telephone=no"> <% String path = request.getContextPath(); String rootPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/"; String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path; request.setAttribute("basePath", basePath); request.setAttribute("rootPath", rootPath); pageContext.setAttribute("newLineChar", "\n"); %> <link rel="stylesheet" href="${basePath}/static/layui/css/layui.css" media="all" /> <link rel="stylesheet" href="//at.alicdn.com/t/font_tnyc012u2rlwstt9.css" media="all" /> <link rel="stylesheet" href="${basePath}/static/css/files.css" media="all" /> <style type="text/css"> </style> </head> <body class="childrenBody"> <blockquote class="layui-elem-quote dir_search"> <input id="checkids" type="hidden"> <div class="layui-inline"> <div class="layui-input-inline"> <input type="text" value="/" placeholder="請輸入HFDS目錄" style="width:800px" disabled="disabled" class="layui-input search_input"> </div> <!-- <a class="layui-btn layui-btn-lg search_btn" id="search">查詢</a> #該方式被放棄--> <p class="layui-form-mid layui-word-aux">提示:ctrl(cmd)+backspace 返回上一級</p> </div> </blockquote> <div class="layui-form dirs_list"> <table class="layui-table"> <colgroup> <col width="50"> <col> <col width="10%"> <col width="10%"> <col width="10%"> <col width="10%"> <col width="15%"> <col width="15%"> <col width="18%"> </colgroup> <thead> <tr> <th><input type="checkbox" lay-skin="primary" lay-filter="allChoose" id="allChoose"></th> <th>權限</th> <th>所屬</th> <th>組別</th> <th>類型</th> <th>大小</th> <th>上次修改</th> <th>名稱</th> <th>操做</th> </tr> </thead> <tbody class="files_content" ></tbody> </table> </div> <div id="page"></div> <script type="text/javascript" src="${basePath}/static/js/jquery.js"></script> <script type="text/javascript" src="${basePath}/static/layui/layui.js"></script> <script type="text/javascript"> $(function(){ //初始化列表及分頁 submit(); //點擊查詢時觸發(該功能使用綁定回車標籤實現-也就是刷新) // $("#search").click(function(){ // //當點擊搜索的時候,起始搜索值爲0-10,且當前頁回到第一頁 // startPage = 0; // currentPage = 1; // submit(); // }) }); //分頁參數設置 這些全局變量關係到分頁的功能 var startPage = 0; var limitNum = 10; var currentPage = 1; var totalPage = 0; //ajax請求後臺數據 function submit(){ var path = $(".search_input").val() $.ajax({ type:"post", async:false, url:"${basePath}/file/fileListByPage.htm", data:{start:startPage, limit:limitNum,path:path}, success:function(data,status){ data=eval("("+data+")"); //轉爲對象 startPage = data.currentIndex;//當前頁數(後臺返回) totalPage = data.totalPage;//總頁數(後臺返回) toPage(data.dataList); } }); } //看看參數有的是否爲空(data:後臺數據) function toPage(data){ layui.use(['form', 'layer', 'layedit', 'laydate', 'laypage'], function() { var form = layui.form(), layer = layui.layer, layedit = layui.layedit, laydate = layui.laydate, laypage = layui.laypage; //調用分頁 laypage({ cont: 'page' ,pages: totalPage ,curr: currentPage ,skip: true ,jump: function(obj, first){ currentPage = obj.curr; startPage = (obj.curr-1)*limitNum; getBackDatas(data); //渲染數據 if(!first){ //加此判斷,避免初始時會無限刷新 submit(); //必定要把翻頁的ajax請求放到這裏,否則會請求兩次。 } form.render(); } }); //全選 form.on('checkbox(allChoose)', function (data) { var checkvals=""; var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])'); child.each(function (index, item) { item.checked = data.elem.checked; if(item.checked){ checkvals += ","+item.value; } }); //捕捉被選記錄個數及id $("#checkids").attr("valength",checkvals.split(",").length-1); $("#checkids").val(checkvals); form.render('checkbox'); }); //經過判斷文章是否所有選中來肯定全選按鈕是否選中 form.on("checkbox(choose)", function (data) { var checkvals=""; var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])'); var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked') if (childChecked.length == child.length) { $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true; } else { $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false; } //遍歷被選中的記錄 for(var i=0;i<childChecked.length;i++){ checkvals += ","+childChecked[i].value; } //捕捉被選記錄個數及id $("#checkids").attr("valength",childChecked.length); $("#checkids").val(checkvals); form.render('checkbox'); }) }); }; //遍歷裝載數據 function getBackDatas(data){ var htmlStr = ""; $.each(data,function(v,o){ htmlStr+="<tr><td><input type=\"checkbox\" lay-skin=\"primary\" class='cd_checkbox' value=\""+o.id+"\" lay-filter=\"choose\"></td>"; htmlStr+='<td>'+o.permission+'</td>'; htmlStr+='<td>'+o.owner+'</td>'; htmlStr+='<td>'+o.group+'</td>'; htmlStr+='<td>'; if(o.type == 'd'){ htmlStr+='目錄'; }else{ htmlStr+='文件'; } htmlStr+='</td>'; htmlStr+='<td>'+o.size+'</td>'; htmlStr+='<td>'+o.modificationTime+'</td>'; htmlStr+='<td>'+o.name+'</td>'; htmlStr+='<td>'; if(o.type == 'f'){ htmlStr+='<a class=\"layui-btn layui-btn-mini data_down\" onclick=\"data_down(\''+o.dirs+'\')\"><i class=\"layui-icon\"></i>下載</a>'; }else{ htmlStr+='<a class=\"layui-btn layui-btn-mini data_up\" onclick=\"data_up(\''+o.dirs+'\')\"><i class=\"layui-icon\"></i>上傳</a>'; htmlStr+='<a class=\"layui-btn layui-btn-mini data_next\" onclick=\"data_next(\''+o.dirs+'\')\"><i class=\"layui-icon\"></i>進入</a>'; } htmlStr+='<a class=\"layui-btn layui-btn-danger layui-btn-mini data_del\" onclick=\"data_del(\''+o.dirs+'\')\" data-id=\"'+o.id+'\"><i class=\"layui-icon\"></i>刪除</a>'; htmlStr+='</td></tr>'; }); if(data.length>0){ $("#page").show(); $(".files_content").html(htmlStr); }else{ $("#page").hide(); $(".files_content").html("<tr><td colspan='9'>暫無數據</td></tr>"); } //清空checkids(checkbox記錄) $("#checkids").attr("valength",0); $("#checkids").val(""); } //前一個目錄(暫時沒用) function data_prev(dirs,pathName){ $(".search_input").val(dirs.replace(pathName,'')); submit(); } //後一個目錄 function data_next(dirs){ $(".search_input").val(dirs); submit(); } function data_up(remoteDir){ layer.prompt({ value: '舉慄 D:/wx/install.txt', title: '請輸入本地文件路徑', maxlength: 100 }, function(value, index){ var dirRegex = /^([A-Za-z]{1}:\/[\w\/]*)?\w+\.{1}[a-zA-Z]+$/; if(!dirRegex.exec(value)){ layui.layer.alert('友情提示:請輸入正確的目錄</br>注意:間隔符爲 / 且目錄不能有特殊字符', { skin: 'layui-layer-molv' ,closeBtn: 0 }); }else{ $.ajax({ type : "POST", async : false, dataType : "JSON", cache : false, url : "${basePath}/file/fileup.htm", data : {localFile:value, remoteDir:remoteDir}, success : function(data) { if (data.flag) { layer.msg(data.msg, { icon:data.msgIcon, time:data.msgTime }); } else { layer.msg(data.msg, { icon:data.msgIcon, time:data.msgTime }); } } }); } layer.close(index); }); } function data_down(remoteFile){ layer.prompt({ value: '舉慄 D:/download', title: '請輸入本地目錄', maxlength: 100 }, function(value, index){ var dirRegex = /^([A-Za-z]{1}:\/[\w\/]*)?\w+[/|\w]$/; if(!dirRegex.exec(value)){ layui.layer.alert('友情提示:請輸入正確的目錄</br>注意:間隔符爲 / 且目錄不能有特殊字符', { skin: 'layui-layer-molv' ,closeBtn: 0 }); }else{ $.ajax({ type : "POST", async : false, dataType : "JSON", cache : false, url : "${basePath}/file/filedown.htm", data : {remoteFile:remoteFile, targetDir:value}, success : function(data) { if (data.flag) { layer.msg(data.msg, { icon:data.msgIcon, time:data.msgTime }); } else { layer.msg(data.msg, { icon:data.msgIcon, time:data.msgTime }); } } }); } layer.close(index); }); } function data_del(remoteFileOrDir){ layer.confirm('友情提示:你肯定要刪除該文件或文件夾嗎', {skin: 'layui-layer-molv' }, function(index){ $.ajax({ type : "POST", async : false, dataType : "JSON", cache : false, url : "${basePath}/file/fileordirdel.htm", data : {remoteFileOrDir:remoteFileOrDir}, success : function(data) { if (data.flag) { layer.msg(data.msg, { icon:data.msgIcon, time:data.msgTime }, function(){ submit(); }); } else { layer.msg(data.msg, { icon:data.msgIcon, }); } } }); layer.close(index); }); } //綁定搜索框回車事件(暫未使用) // $('.search_input').bind('keypress', function (event) { // if(event.keyCode == "13") { // submit(); // } // }) //監聽按鍵事件 document.onkeydown = function(e) { var keyCode = e.keyCode || e.which || e.charCode; var ctrlKey = e.ctrlKey || e.metaKey; if(keyCode == 8) { var sval = $('.search_input').val(); if(sval!=''&&sval.substring(0,1)=='/'&&sval!='/'){ var prevdir; if(sval.substring(sval.length-1)!='/'){ prevdir = sval.substring(0,sval.lastIndexOf("/")); $(".search_input").val(prevdir); } if(prevdir==''){ $('.search_input').val('/'); } //重置開始頁面數 startPage=0; submit(); } } //e.preventDefault(); return true; } </script> </body> </html>
3、控制器前端
package com.ebd.application.modules.fileManage.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.ebd.application.common.Base.Page; import com.ebd.application.common.support.RetObj; import com.ebd.application.modules.fileManage.pojo.FilesOrDirs; import com.ebd.application.modules.fileManage.service.FileService; @Controller @Scope("prototype") @RequestMapping("/file") public class FileController { // 日誌記錄器 public final Logger log = Logger.getLogger(this.getClass()); @Autowired private FileService fileService; @RequestMapping("filemanage") public String fileManage(HttpServletRequest request, String currPage) { return "modules/file/filemanage"; } @ResponseBody @RequestMapping("fileListByPage") public Page<FilesOrDirs> listByPage(Integer start, Integer limit, String path) { Map<String,Object> conditions = new HashMap<String,Object>(); conditions.put("path", StringUtils.isNotBlank(path) ? path : "/"); Page<FilesOrDirs> page = new Page<FilesOrDirs>(start,limit,conditions); return fileService.findByPage(page); } @ResponseBody @RequestMapping("fileup") public RetObj fileUp(String localFile, String remoteDir) { return fileService.fileUp(localFile,remoteDir); } @ResponseBody @RequestMapping("filedown") public RetObj fileDown(String remoteFile, String targetDir) { return fileService.fileDown(remoteFile,targetDir); } @ResponseBody @RequestMapping("fileordirdel") public RetObj fileOrDirDel(String remoteFileOrDir) { return fileService.fileOrDirDel(remoteFileOrDir); } }
4、FileDao類java
package com.ebd.application.modules.fileManage.dao; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.mapred.JobConf; import com.ebd.application.common.Base.Constants; import com.ebd.application.common.Base.Page; import com.ebd.application.common.support.RetObj; import com.ebd.application.common.utils.CreateFileUtil; import com.ebd.application.common.utils.DateUtils; import com.ebd.application.common.utils.Identities; import com.ebd.application.modules.fileManage.pojo.FilesOrDirs; public class FileDao { //hdfs路徑 private static String hdfsPath; //Hadoop系統配置 private static Configuration conf; //fdfs對象 private static FileDao hdfsObj; private static List<FilesOrDirs> filesList = null; public FileDao(Configuration conf) { this(Constants.HDFS, conf); } public FileDao(String hdfs, Configuration conf) { this.hdfsPath = hdfs; this.conf = conf; } public static FileDao getHdfsObj() { if(hdfsObj == null){ return new FileDao(config()); } return hdfsObj; } public static int getCount(Page<FilesOrDirs> page) { int count = 0; try { count = count(page); } catch (Exception e) { e.printStackTrace(); } return count; } public static List<FilesOrDirs> findByPage(Page<FilesOrDirs> page) { List<FilesOrDirs> filesList = null; try { filesList = getHdfsObj().ls(page); } catch (Exception e) { e.printStackTrace(); } return filesList; } public static JobConf config(){ JobConf conf = new JobConf(FileDao.class); conf.setJobName("HdfsDAO"); conf.addResource("hadoop/core-site.xml"); conf.addResource("hadoop/hdfs-site.xml"); conf.addResource("hadoop/mapred-site.xml"); return conf; } public static int count(Page<FilesOrDirs> page){ int count = 0; try { Path path = new Path(Constants.HDFS+page.getCondition().get("path")); FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf); FileStatus[] fileArray = fs.listStatus(path); if(fileArray != null){ filesList = new ArrayList<FilesOrDirs>(); for (FileStatus f : fileArray) {count++;} } fs.close(); } catch (Exception e) { return count; } return count; } public List<FilesOrDirs> ls(Page<FilesOrDirs> page){ int count = 1; try { Path path = new Path(Constants.HDFS+page.getCondition().get("path")); FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf); FileStatus[] fileArray = fs.listStatus(path); if(fileArray != null){ filesList = new ArrayList<FilesOrDirs>(); if(fileArray.length>page.getStart()){ for(int i = page.getStart(); i<fileArray.length; i++){ count++; if(count<page.getLimit()){ FilesOrDirs fd = new FilesOrDirs(); fd.setId(Identities.uuid()); fd.setName(fileArray[i].getPath().getName()); fd.setGroup(fileArray[i].getGroup()); fd.setModificationTime(DateUtils.timestamptoString(fileArray[i].getModificationTime())); fd.setOwner(fileArray[i].getOwner()); fd.setPermission(fileArray[i].getPermission().toString()); fd.setSize(String.format("%d", fileArray[i].getLen())); fd.setType(fileArray[i].isDirectory()?Constants.IS_DIR:Constants.IS_FILE); fd.setDirs(fileArray[i].getPath().toString().substring(Constants.HDFS.length())); filesList.add(fd); } } } } fs.close(); } catch (IOException e) { return filesList; } return filesList; } public static RetObj fileUp(String localFile, String remoteDir) { try { FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf); fs.copyFromLocalFile(new Path(localFile), new Path(remoteDir)); fs.close(); } catch (Exception e) { return RetObj.getRetObj(false,Constants.MSG_UPLOAD_FAILED,2,1000); } return RetObj.getRetObj(true,Constants.MSG_UPLOAD_SUCCESS,1,1000); } public static RetObj fileDown(String remoteFile, String targetDir) { try { FileSystem fs = FileSystem.get(URI.create(remoteFile),conf); FSDataInputStream fsdi = fs.open(new Path(remoteFile)); if(CreateFileUtil.createDir(targetDir)){ OutputStream output = new FileOutputStream(targetDir+remoteFile.substring(remoteFile.lastIndexOf("/"))); IOUtils.copyBytes(fsdi,output,4096,true); } fs.close(); } catch (Exception e) { return RetObj.getRetObj(false,Constants.MSG_DOWNLOAD_FAILED,2,1000); } return RetObj.getRetObj(true,Constants.MSG_DOWNLOAD_SUCCESS,1,1000); } public static RetObj fileOrDirDel(String remoteFileOrDir) { try { Path path = new Path(remoteFileOrDir); FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf); fs.deleteOnExit(path); fs.close(); } catch (Exception e) { return RetObj.getRetObj(false,Constants.MSG_CRUD_FAILED,2,1000); } return RetObj.getRetObj(true,Constants.MSG_CRUD_SUCCESS,1,1000); } }
Page類python
package com.ebd.application.common.Base; import java.util.List; import java.util.Map; public class Page<T> { /** 總記錄數 */ private int total; /** 分頁結果 */ private List<T> dataList; /** 開始頁碼 */ private int start; /** 每頁多少 */ private int limit; /** 查詢條件 */ private Map<String,Object> condition; private int currentPage; //當前頁 private int currentIndex; //當前記錄起始索引 private int totalPage; //總頁數 public Page(int start, int limit) { this.start = start; this.limit = limit; } public Page(int start, int limit, Map<String,Object> condition) { this.start = start; this.limit = limit; this.condition = condition; } public int getCurrentPage() { if(currentPage<=0) currentPage = 1; return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getCurrentIndex() { this.currentIndex = (getCurrentPage()-1)*getLimit(); if(currentIndex<0) currentIndex = 0; return currentIndex; } public void setCurrentIndex(int currentIndex) { this.currentIndex = currentIndex; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotal() { return total; } public void setTotal(int total) { if(total%limit==0) totalPage = total/limit; else totalPage = total/limit+1; this.total = total; } public List<T> getDataList() { return dataList; } public void setDataList(List<T> dataList) { this.dataList = dataList; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public Map<String, Object> getCondition() { return condition; } public void setCondition(Map<String, Object> condition) { this.condition = condition; } }
效果圖jquery