目录
1.功能展示截图
2.实现代码
2.1HTML页面代码
2.2后台代码
2.2.1项目结构
2.2.2项目代码
其他问题
1.功能展示截图
项目中需要用到文件管理来自由控制文件的上传、下载、删除等,就想到做一个简单的在线文件管理功能。
支持在线编辑:
2.实现代码
2.1HTML页面代码
必要引入:
<!-- <link rel="stylesheet" href="/assets/css/glyphicons.css"> -->
<script src="/assets/js/old/jquery.min.js"></script>
<script src="/assets/js/angular.min.js"></script>
<script src="/assets/js/angular-translate.min.js"></script>
<script src="/assets/js/ng-file-upload.min.js"></script>
<script src="/assets/js/old/bootstrap.min.js"></script>
<link rel="stylesheet" href="/assets/css/old/bootstrap.min.css" />
<!-- <link href="/assets/css/angular-filemanager.min.css" rel="stylesheet"> -->
<script src="/assets/js/angular-filemanager.min.js"></script>
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" data-ng-app="FileManagerApp" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head><th:block th:include="include :: header('文件上传下载分析列表')" /><meta http-equiv="X-UA-Compatible" content="I EmulateIE8" /><!-- <link rel="shortcut icon" href="/assets/img/efo-favicon.png" /> --><link type="text/css" th:href="@{/css/glyphicons.css}" rel="stylesheet" /><script type="text/javascript" th:src="@{/js/jquery.min.js}"></script><script type="text/javascript" th:src="@{/js/angular.min.js}"></script><script type="text/javascript" th:src="@{/js/angular-translate.min.js}"></script><script type="text/javascript" th:src="@{/js/ng-file-upload.min.js}"></script><script type="text/javascript" th:src="@{/js/bootstrap.min.js}"></script><link type="text/css" th:href="@{/css/bootstrap.min.css}" rel="stylesheet" /><link type="text/css" th:href="@{/css/angular-filemanager.min.css}" rel="stylesheet" /><script type="text/javascript" th:src="@{/js/angular-filemanager.min.js}"></script><script type="text/javascript">angular.module('FileManagerApp').config(['fileManagerConfigProvider', function (config) {var defaults = config.$get();config.set({appName: '远程文件管理',pickCallback: function (item) {var msg = 'Picked %s "%s" for external use'.replace('%s', item.type).replace('%s', item.fullPath());window.alert(msg);},allowedActions: angular.extend(defaults.allowedActions, {pickFiles: false,pickFolders: false})});}]);</script>
</head>
<body id="particles-js" class="gray-bg ng-cloak">
<!-- <body class="gray-bg ng-cloak" id="particles-js"> -->
<!-- <h1>测试</h1> --><angular-filemanager></angular-filemanager>
<!-- <th:block th:include="include :: footer" /> -->
</body>
</html>
2.2后台代码
2.2.1项目结构
2.2.2项目代码
DefaultValues.java
package com.ruoyi.efo.modules.constant;import com.zhazhapan.modules.constant.ValueConsts;/*** @author t* @since xx*/
public class DefaultValues {/*** 未分类*/public static final String UNCATEGORIZED = "未分类";/*** 404页面路径*/public static final String NOT_FOUND_PAGE = "/404.html";/*** Controller包路径*/public static final String CONTROLLER_PACKAGE = "com.zhazhapan.efo.web.controller";/*** 配置文件路径*/public static final String SETTING_PATH = "/config.json";/*** 冒号*/public static final String COLON = ":";/*** 默认存储路径*/public static final String STORAGE_PATH = ValueConsts.USER_HOME + ValueConsts.SEPARATOR + "Desktop" + ValueConsts.SEPARATOR;/*** 首页映射路径*/public static final String INDEX_PAGE = "/index";/*** 配置映射的路径*/public static final String CONFIG_PAGE = "/config";/*** 资源映射的路径*/public static final String ASSETS_PAGE = "/assets";/*** 登陆注册页面映射路径*/public static final String SIGNIN_PAGE = "/signin";/*** 管理员页面映射路径*/public static final String ADMIN_PAGE = "/admin";/*** int型数值3*/public static final int THREE_INT = 3;/*** int型数值2*/public static final int TWO_INT = 2;/*** code字符*/public static final String CODE_STRING = "code";private DefaultValues() {}
}
IFileManagerService
package com.ruoyi.efo.service;import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/*** @author xx* @since 2023/7/7*/
public interface IFileManagerService {/*** 下载多个文件** @param response {@link HttpServletResponse}* @param items 文件集* @param destFile 目标文件名** @throws IOException 异常*/void multiDownload(HttpServletResponse response, String[] items, String destFile) throws IOException;/*** 上传文件(暂时还没有实现)** @param destination 目标文件* @param files {@link MultipartFile}** @return {@link JSONObject}*/JSONObject upload(String destination, MultipartFile... files);/*** 解压文件** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject extract(JSONObject object);/*** 压缩文件** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject compress(JSONObject object);/*** 设置文件权限** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject setPermission(JSONObject object);/*** 创建文件夹** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject createFolder(JSONObject object);/*** 获取文件内容** @param object {@link JSONObject}** @return 文件内容*/String getContent(JSONObject object);/*** 编辑文件** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject edit(JSONObject object);/*** 移除文件** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject remove(JSONObject object);/*** 复制文件** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject copy(JSONObject object);/*** 移动文件** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject move(JSONObject object);/*** 重命名** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONObject rename(JSONObject object);/*** 列出文件** @param object {@link JSONObject}** @return {@link JSONObject}*/JSONArray list(JSONObject object);
}
FileManagerServiceImpl
package com.ruoyi.efo.service.impl;import cn.hutool.core.util.ZipUtil;import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.efo.modules.constant.DefaultValues;
import com.ruoyi.efo.service.IFileManagerService;
import com.zhazhapan.modules.constant.ValueConsts;
import com.zhazhapan.util.Checker;
import com.zhazhapan.util.FileExecutor;
import com.zhazhapan.util.Formatter;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.IOException;
import java.util.Date;/*** @author xx* @since 2023/7/7*/
@Service
public class FileManagerServiceImpl implements IFileManagerService {private static Logger logger = Logger.getLogger(FileManagerServiceImpl.class);@Overridepublic void multiDownload(HttpServletResponse response, String[] items, String destFile) throws IOException {File zip = ZipUtil.zip(new File(ValueConsts.USER_DESKTOP + File.separator + destFile), ValueConsts.FALSE,FileExecutor.getFiles(items));if (zip.exists()) {response.getOutputStream().write(FileExecutor.readFileToByteArray(zip));FileExecutor.deleteFile(zip);}}@Overridepublic JSONObject upload(String destination, MultipartFile... files) {System.out.println(files.length);if (Checker.isNotEmpty(files)) {if (Checker.isWindows() && destination.length() < ValueConsts.TWO_INT) {destination = "C:";}for (MultipartFile file : files) {if (Checker.isNotNull(file) && !file.isEmpty()) {try {file.transferTo(new File(destination + File.separator + file.getOriginalFilename()));} catch (IOException e) {logger.error(e.getMessage());return getBasicResponse(ValueConsts.FALSE);}}}}return getBasicResponse(ValueConsts.TRUE);}@Overridepublic JSONObject extract(JSONObject object) {String destination = object.getString("destination") + File.separator + object.getString("folderName");String zipFile = object.getString("item");return getBasicResponse(ZipUtil.unzip(zipFile, destination).exists());}@Overridepublic JSONObject compress(JSONObject object) {JSONArray array = object.getJSONArray("items");File[] files = new File[array.size()];int i = 0;for (Object file : array) {files[i++] = new File(file.toString());}String dest = object.getString("destination");String name = object.getString("compressedFilename");File zip = ZipUtil.zip(new File(dest + File.separator + name), ValueConsts.FALSE, files);return getBasicResponse(zip.exists());}@Overridepublic JSONObject setPermission(JSONObject object) {if (Checker.isLinux()) {JSONArray array = object.getJSONArray("items");int code = object.getInteger("permsCode");for (Object file : array) {try {Runtime.getRuntime().exec("chmod -R " + code + " " + file.toString());} catch (IOException e) {logger.error(e.getMessage());return getBasicResponse(ValueConsts.FALSE);}}}return getBasicResponse(ValueConsts.TRUE);}@Overridepublic JSONObject createFolder(JSONObject object) {String folder = object.getString("newPath");return getBasicResponse(FileExecutor.createFolder(folder));}@Overridepublic String getContent(JSONObject object) {String fileName = object.getString("item");try {return FileExecutor.readFile(fileName);} catch (IOException e) {logger.error(e.getMessage());return "";}}@Overridepublic JSONObject edit(JSONObject object) {String file = object.getString("item");String content = object.getString("content");try {FileExecutor.saveFile(file, content);return getBasicResponse(ValueConsts.TRUE);} catch (IOException e) {logger.error(e.getMessage());return getBasicResponse(ValueConsts.FALSE);}}@Overridepublic JSONObject remove(JSONObject object) {JSONArray array = object.getJSONArray("items");array.forEach(file -> FileExecutor.deleteFile(file.toString()));return getBasicResponse(ValueConsts.TRUE);}@Overridepublic JSONObject copy(JSONObject object) {JSONArray array = object.getJSONArray("items");String dest = object.getString("newPath");File[] files = new File[array.size()];int i = 0;for (Object file : array) {files[i++] = new File(file.toString());}try {FileExecutor.copyFiles(files, dest);return getBasicResponse(ValueConsts.TRUE);} catch (IOException e) {logger.error(e.getMessage());return getBasicResponse(ValueConsts.FALSE);}}@Overridepublic JSONObject move(JSONObject object) {JSONArray array = object.getJSONArray("items");String dest = object.getString("newPath");for (Object file : array) {try {FileExecutor.moveToDirectory(new File(file.toString()), new File(dest), ValueConsts.TRUE);} catch (IOException e) {logger.error(e.getMessage());return getBasicResponse(ValueConsts.FALSE);}}return getBasicResponse(ValueConsts.TRUE);}@Overridepublic JSONObject rename(JSONObject object) {String fileName = object.getString("item");String newFileName = object.getString("newItemPath");FileExecutor.renameTo(fileName, newFileName);return getBasicResponse(ValueConsts.TRUE);}@Overridepublic JSONArray list(JSONObject object) {String path = object.getString("path");JSONArray array = new JSONArray();File[] files = null;if (Checker.isWindows()) {if (Checker.isNotEmpty(path) && path.startsWith(ValueConsts.SPLASH_STRING)) {path = path.substring(1);}if (Checker.isEmpty(path)) {FileSystemView fsv = FileSystemView.getFileSystemView();File[] fs = File.listRoots();for (File file : fs) {if (file.getTotalSpace() > 0) {String displayName = fsv.getSystemDisplayName(file);int len = displayName.length();JSONObject jsonObject = new JSONObject();jsonObject.put("name", displayName.substring(len - 3, len - 1));jsonObject.put("rights", "----------");jsonObject.put("size", file.getTotalSpace() - file.getFreeSpace());jsonObject.put("date", Formatter.datetimeToString(new Date(file.lastModified())));jsonObject.put("type", file.isDirectory() ? "dir" : "file");array.add(jsonObject);}}} else if (path.startsWith(DefaultValues.COLON, 1)) {files = FileExecutor.listFile(path.endsWith(DefaultValues.COLON) ? path + File.separator : path);} else {logger.error("path error");}} else {files = FileExecutor.listFile(Checker.isEmpty(path) ? "/" : (path.startsWith("/") ? path : "/" + path));}if (Checker.isNotNull(files)) {for (File file : files) {JSONObject jsonObject = new JSONObject();jsonObject.put("name", file.getName());jsonObject.put("rights", "----------");jsonObject.put("size", file.length());jsonObject.put("date", Formatter.datetimeToString(new Date(file.lastModified())));jsonObject.put("type", file.isDirectory() ? "dir" : "file");array.add(jsonObject);}}return array;}private JSONObject getBasicResponse(boolean isSuccess) {JSONObject jsonObject = new JSONObject();if (isSuccess) {jsonObject.put("success", true);jsonObject.put("error", null);} else {jsonObject.put("success", null);jsonObject.put("error", "服务器异常");}return jsonObject;}
}
ControllerUtils
package com.ruoyi.efo.util;import com.alibaba.fastjson.JSONObject;
import com.ruoyi.efo.modules.constant.DefaultValues;
import com.zhazhapan.util.Checker;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;/*** @author xx* @since 2023/7/7*/
public class ControllerUtils {private ControllerUtils() {}/*** 获取一个简单的响应状态** @param isSuccess 是否操作成功** @return 响应JSON字符串*/public static String getResponse(boolean isSuccess) {JSONObject jsonObject = new JSONObject();if (isSuccess) {jsonObject.put("status", "success");} else {jsonObject.put("status", "error");}return jsonObject.toString();}/*** 加载本地资源** @param response 返回的Response* @param path 资源路径* @param download 直接下载*/public static void loadResource(HttpServletResponse response, String path, boolean download) throws IOException {if (Checker.isNotEmpty(path)) {File file = new File(path);if (download) {setResponseFileName(response, file.getName());}FileInputStream in = new FileInputStream(file);ServletOutputStream os = response.getOutputStream();byte[] b;while (in.available() > 0) {b = in.available() > 1024 ? new byte[1024] : new byte[in.available()];in.read(b, 0, b.length);os.write(b, 0, b.length);}in.close();os.flush();os.close();} else {response.sendRedirect(DefaultValues.NOT_FOUND_PAGE);}}/*** 设置响应头的文件名** @param response {@link HttpServletResponse}* @param fileName 文件名*/public static void setResponseFileName(HttpServletResponse response, String fileName) throwsUnsupportedEncodingException {response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));}
}
FileMangerController
package com.ruoyi.efo.web.controller;import java.io.IOException;
import java.util.Map;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;import com.alibaba.fastjson.JSONObject;
import com.ruoyi.efo.service.IFileManagerService;
import com.ruoyi.efo.util.ControllerUtils;
import com.zhazhapan.modules.constant.ValueConsts;
import com.zhazhapan.util.ArrayUtils;import springfox.documentation.annotations.ApiIgnore;/*** <a href="https://github.com/joni2back/angular-filemanager/blob/master/API.md">see api doc</a>** @author xx* @since 2023/7/7*/
@ApiIgnore
@RestController
@RequestMapping("/filemanager")
//@AuthInterceptor(InterceptorLevel.SYSTEM)
public class FileMangerController{@Autowiredprivate IFileManagerService fileManagerService;JSONObject jsonObject = new JSONObject();// @Autowired
// public FileMangerController2(IFileManagerService fileManagerService, JSONObject jsonObject) {
// this.fileManagerService = fileManagerService;
// this.jsonObject = jsonObject;
// }// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/multidownload", method = RequestMethod.GET)public void multiDownload(HttpServletResponse response, String[] items, String toFilename) throws IOException {ControllerUtils.setResponseFileName(response, toFilename);fileManagerService.multiDownload(response, items, toFilename);}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/download", method = RequestMethod.GET)public void download(HttpServletResponse response, String path) throws IOException {ControllerUtils.loadResource(response, path, ValueConsts.TRUE);}/*** 暂时没有找到更好的解决方案** @param destination 目的** @return 响应结果*/
// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/upload", method = RequestMethod.POST)public String upload(String destination, MultipartHttpServletRequest request) {Map<String, MultipartFile> fileMap = request.getFileMap();MultipartFile[] files = ArrayUtils.mapToArray(fileMap, MultipartFile.class);jsonObject.put("result", fileManagerService.upload(destination, files));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/extract", method = RequestMethod.POST)public String extract(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.extract(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/compress", method = RequestMethod.POST)public String compress(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.compress(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/permission", method = RequestMethod.POST)public String setPermission(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.setPermission(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/folder", method = RequestMethod.POST)public String createFolder(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.createFolder(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/content", method = RequestMethod.POST)public String getContent(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.getContent(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/edit", method = RequestMethod.POST)public String edit(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.edit(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/remove", method = RequestMethod.POST)public String remove(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.remove(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/copy", method = RequestMethod.POST)public String copy(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.copy(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/move", method = RequestMethod.POST)public String move(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.move(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/rename", method = RequestMethod.POST)public String rename(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.rename(json));return jsonObject.toJSONString();}// @AuthInterceptor(InterceptorLevel.SYSTEM)@RequestMapping(value = "/list", method = RequestMethod.POST)public String list(@RequestBody JSONObject json) {jsonObject.put("result", fileManagerService.list(json));return jsonObject.toJSONString();}
}
其他问题
pom引入,其他包自行引入即可
<dependency>
<groupId>com.zhazhapan</groupId>
<artifactId>util</artifactId>
<version>1.1.0</version>
</dependency>