ztree+ajax實現(xiàn)文件樹下載功能
基于java實現(xiàn)文件樹下載,供大家參考,具體內(nèi)容如下
0.項目準備工作
1.前端用到的插件庫:
ztree官網(wǎng)

2.后端maven依賴:
<dependencies>
<!-- servlet依賴 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- springMVC依賴 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<!-- 文件上傳的jar包 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
// gson可以不要,這是我測試時使用的
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
3.web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 聲明springMvc的核心對象 DispatcherServlet -->
<servlet>
<servlet-name>web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springConfig.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>web</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
<!-- 注冊字符集過濾器,解決post請求的中文亂碼問題-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4.springConfig.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 開啟組件掃描 -->
<context:component-scan base-package="com.file"></context:component-scan>
<!--聲明 配置springMVC視圖解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前綴:視圖文件的路徑-->
<property name="prefix" value="/WEB-INF/view/" />
<!--后綴:視圖文件的擴展名-->
<property name="suffix" value=".jsp" />
</bean>
<!--讀寫JSON的支持(Jackson)-->
<mvc:annotation-driven />
<!-- 配置多媒體解析 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 配置字符編碼集 -->
<property name="defaultEncoding" value="utf-8"> </property>
<!-- 配置文件上傳大小 單位是字節(jié) -1代表沒有限制 maxUploadSizePerFile是限制每個上傳文件的大小,而maxUploadSize是限制總的上傳文件大小 -->
<property name="maxUploadSizePerFile" value="-1"> </property>
<!-- ,不設置默認不限制總的上傳文件大小,這里設置總的上傳文件大小不超過1M(1*1024*1024) -->
<property name="maxUploadSize" value="1048576"/>
</bean>
</beans>
1.效果展示:
服務器端的文件目錄:



2.思路分析
1、需要遞歸遍歷某個目錄,并且判斷是目錄還是文件
2、找到父目錄和子文件的關(guān)系,構(gòu)建文件對象,將該對象加入到list集合中
3、將list集合轉(zhuǎn)為json,返回給前端進行渲染
4、前端渲染出來的每個文件都包含一個該文件對應的下載url,點擊該文件跳轉(zhuǎn)到該文件的下載接口
5、提供下載接口,前端需要傳遞一個文件名稱,然后后端根據(jù)文件名稱去遍歷指定的目錄,查詢是否有該文件,如果有,則將該文件進行下載
先來看下如果遞歸遍歷獲取到某個目錄下的所有文件:
public class Test2 {
public static void main(String[] args) {
File file = new File("D:\\IDE2019");
listFile(file);
}
public static void listFile(File file ) {
// 判斷該文件是否存在
if (file.exists()){
// 獲取當前文件夾下的所有子文件
File[] files = file.listFiles();
if (files!=null&&files.length>0){
// 對該文件夾進行遍歷
for (int i = 0; i < files.length; i++) {
// // 如果是一個目錄繼續(xù)進行遞歸
if (files[i].exists()&&files[i].isDirectory()){
listFile(files[i]);
}else {
// 不是目錄,是一個文件,則輸出文件名
System.out.println(files[i].getName());
}
}
}
}
}
}
3.前端實現(xiàn)代碼:
代碼:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../css/zTreeStyle/zTreeStyle.css" rel="external nofollow" type="text/css">
<script type="text/javascript" src="../../js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="../../js/jquery.ztree.core.min.js"></script>
<title>文件下載</title>
</head>
<body>
<script>
var settingss = {
//zTree 的唯一標識,初始化后,等于 用戶定義的 zTree 容器的 id 屬性值。
treeId:"treeDemo",
data: {
simpleData: {
enable: true, //true 、 false 分別表示 使用 、 不使用 簡單數(shù)據(jù)模式
idKey: "id", //節(jié)點數(shù)據(jù)中保存唯一標識的屬性名稱
pIdKey: "pId", //節(jié)點數(shù)據(jù)中保存其父節(jié)點唯一標識的屬性名稱
rootPId: "0" //用于修正根節(jié)點父節(jié)點數(shù)據(jù),即 pIdKey 指定的屬性值
},
key: {
name: "name" //zTree 節(jié)點數(shù)據(jù)保存節(jié)點名稱的屬性名稱 默認值:"name"
}
},
check:{
enable:true, //true 、 false 分別表示 顯示 、不顯示 復選框或單選框
nocheckInherit:false, //當父節(jié)點設置 nocheck = true 時,設置子節(jié)點是否自動繼承 nocheck = true
chkboxType: { "Y": "p", "N": "s" }
},
};
$(document).ready(function(){
$.ajax({
type:"get",
url:"/file/init.mvc",
async:true,
success:function(result){
console.log(result)
// 得到ajax返回的數(shù)據(jù) 并且初始化文件樹
var zTreeObj = $.fn.zTree.init($("#treeDemo"), settingss, result); //初始化樹
zTreeObj.expandAll(false); //true 節(jié)點全部展開、false節(jié)點收縮
}
});
});
</script>
<div>
<ul id="treeDemo" class="ztree"></ul>
</div>
</body>
</html>
4.后端代碼實現(xiàn):
1.抽象出來的實例對象bean
/**
* @author compass
* @version 1.0
* @date 2021-05-14 22:41
*/
public class MyFile {
private int id;
private int pId;
private String name;
private String url;
public MyFile(int id, int pId, String name, String url) {
this.id = id;
this.pId = pId;
this.name = name;
this.url = url;
}
@Override
public String toString() {
return "MyFile{" +
"id=" + id +
", pId=" + pId +
", name='" + name + '\'' +
", url='" + url + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getpId() {
return pId;
}
public void setpId(int pId) {
this.pId = pId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
2.渲染數(shù)據(jù)和指定文件名查詢文件地址的類
/**
* @author compass
* @version 1.0
* @date 2021-05-15 12:31
*/
public class FilerService {
// 將構(gòu)建為文件對象的文件或目錄放到list集合中
List<MyFile> fileList = new ArrayList<>();
/**
* 功能:遞歸遍歷文件,并且將文件或目錄按照規(guī)定構(gòu)建為對象 撞到List集合返回
* @param file 待遍歷的文件夾
* @param index 掃描文件賦值指針 初始值為 :1
* @return
*/
public List<MyFile> listAll1(File file , int index) {
File[] listFiles= file.listFiles();
// 將文件或目錄構(gòu)建為對象
for (int i=1;i<listFiles.length+1;i++){
if (listFiles[i-1].isDirectory()){
// 如果是目錄 則url為空 pid=0說明是根目錄
MyFile myFile = new MyFile(i,0,listFiles[i-1].getName(),"");
fileList.add(myFile);
}else {
// 如果是文件則拼接下載地址
String filename=listFiles[i-1].getName();
// 文件的id為:(目錄id*100)+文件序列
MyFile myFile = new MyFile((100*index)+i,index,listFiles[i-1].getName(),"http://localhost:8080/file/download.mvc?filename="+filename);
fileList.add(myFile);
}
}
// 判斷該文件是否存在
if (file.exists()){
// 獲取當前文件夾下的所有子文件
File[] files = file.listFiles();
if (files!=null&&files.length>0){
// 對文件進行遍歷
for (int i = 0; i < files.length; i++) {
if (files[i].exists()&&files[i].isDirectory()){
// 如果是一個目錄繼續(xù)進行遞歸 直到找到文件為止 每遍歷一個目錄 index+1
listAll1(files[i],i+1);
}
}
}
}
return fileList;
}
// 制定文件的父目錄
String parentDir=null;
/**
* 根據(jù)傳遞過來的文件名 找到該文件的父文件夾,如果沒有找到返回null
* @param fileName 文件名
* @param dir 需要查找的目錄
* @return
*/
public String getFileName(String fileName,File dir){
if (dir.exists()){
File[] files = dir.listFiles();
if (files!=null&&files.length>0){
for (int i=0;i<files.length;i++){
if (files[i].exists()&&files[i].isDirectory()){
getFileName(fileName,files[i]);
}else {
// 如果找到傳遞過來的文件名則賦值給 parentDir
if (fileName.equals(files[i].getName())){
parentDir=files[i].getParent();
break;
}
}
}
}
}
return parentDir;
}
}
3.下載和渲染數(shù)據(jù)的Controller
/**
* @author compass
* @version 1.0
* @date 2021-05-14 21:43
*/
@Controller
@RequestMapping("/file/")
public class FileDownloadController {
// 提供訪問接口
@GetMapping("downloadIn.mvc")
public String downloadIn(){
return "index";
}
// 初始化頁面數(shù)據(jù)
@ResponseBody
@GetMapping("init.mvc")
public List<MyFile> test(){
File file = new File("D:\\IDE2019\\work");
FilerService service = new FilerService();
// 將制定目錄的文件夾 下的目錄和文件構(gòu)建為MyFile對象裝到List集合中
List<MyFile> listAll1 = service.listAll1(file, 1);
// 返回Json數(shù)據(jù)給前端進行渲染
return listAll1;
}
// 提供下載接口
@GetMapping("download.mvc")
public ResponseEntity <byte[]> fileDownload1(String filename,HttpServletRequest request) throws IOException {
// 指定下載那個目錄下的文件
File file = new File("D:\\IDE2019\\work");
FilerService service = new FilerService();
// 獲取到該文件的父目錄
String path = service.getFileName(filename, file);
// 創(chuàng)建文件下載對象
File downloadFile = new File(path, filename);
HttpHeaders header = new HttpHeaders();
header.setContentDispositionFormData("attachment",filename);
header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
ResponseEntity<byte[]> result = new ResponseEntity<>(FileUtils.readFileToByteArray(downloadFile), header, HttpStatus.OK);
return result;
}
}
測試:可以看到我們每點擊一個文件都可以跳轉(zhuǎn)到我們的下載接口,進行下載的。


這只是一個簡單的使用,還有很多地方需要進行優(yōu)化,當然也可以使用別的方法進行實現(xiàn),這就是算是一個小練習吧,復習一下ajax和遞歸的知識。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ASP.NET與Ajax的實現(xiàn)方式小總結(jié)
Ajax 應該不是一項技術(shù),是一種思想而已,跟 ASP.NET 以及其它 Web 開發(fā)語言沒有什么太大關(guān)系,這里只是談談 ASP.NET 中目前使用的 Ajax 技術(shù)以及其它一些實現(xiàn) Ajax 的優(yōu)秀框架。感興趣的朋友跟著小編一起學習asp.net與ajax的實現(xiàn)方式2015-09-09
ajax動態(tài)賦值echarts的實例(餅圖和柱形圖)
下面小編就為大家分享一篇ajax動態(tài)賦值echarts的實例(餅圖和柱形圖),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
用AJAX實現(xiàn)的無刷新的分頁實現(xiàn)代碼(asp.net)
最近學習了AJAX技術(shù)。AJAX,指的是異步的Javascript和xml。它的基本原理就是頁面用Javascript發(fā)送一個異步的http請求到服務器,服務器返回數(shù)據(jù)后,再用Javascript靜態(tài)的去更改頁面某個地方的值,而無需提交表單。2011-04-04
有關(guān)Ajax中g(shù)et和post的使用問題
下面小編就為大家?guī)硪黄嘘P(guān)Ajax中g(shù)et和post的使用問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06

