package com.example.fms.common.utils; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.IdUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.example.fms.common.model.dto.SystemFileDTO; import com.example.fms.common.model.dto.UploadFileDTO; import okhttp3.*; import okhttp3.Response; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.system.ApplicationHome; import org.springframework.mock.web.MockMultipartFile; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.io.*; import java.net.URL; import java.nio.file.Files; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import static cn.hutool.core.io.FileUtil.getMimeType; @Service public class FileUtils { public static final String FILE_SEPARATOR = System.getProperty("file.separator"); public static final String COMMON_FILE = "file"; public static final String BACKUP_FILE = "backup"; @Autowired private FileUtils fileUtils; public static String getStaticPath(String fileName) { //ApplicationHome类 返回target目录层级 ApplicationHome ah = new ApplicationHome(FileUtils.class); //获取 applicationHome 内的路径 ...\target\classes 到这一层级下 File file = ah.getSource(); //获取 file的parentFile 即最后一级之前的所有层级路径(包括盘符) 这里能获得到的最终层级为 ...\target 后续用FILE_SEPARATOR(系统路径分割通配符 即 "\") 以及fileName拼接生成存放文件的目录层级 即为根目录 root String rootPath = file.getParentFile().toString() + FILE_SEPARATOR + fileName; //根据上方生成的根目录路径 生成对应文件夹 没有就新建 File root = new File(rootPath); if (!root.exists()) { root.mkdir(); } //返回的最终形式为 盘符:\项目层级\target\file return rootPath; } public UploadFileDTO uploadFile(MultipartFile file) { UploadFileDTO fileDTO = new UploadFileDTO(); //以下操作为 先取得传入文件的完整文件名 (文件名 + 后缀) 然后用FileUtil分别取出 文件名 和 不带 "." 的后缀 然后将这些内容装配进 实体中 //file.getOriginFilename 获取源文件 //FileUtil.getPrefix 返回主文件名 fileDTO.setName(FileUtil.getPrefix(file.getOriginalFilename())); //FileUtil.extName 获取文件的扩展名(后缀名),扩展名不带 "." fileDTO.setExtName(FileUtil.extName(file.getOriginalFilename())); //获取目录名 用时间作为目录名称 String directoryName = this.getDirectoryName(); //用IdUtil生成的UUID 与实体中的 extName(后缀名) 拼接后作为文件名 simpleUUID与randomUUID的区别是 simpleUUID 没有 "-" String fileName = IdUtil.simpleUUID() + "." + fileDTO.getExtName(); //将完整文件名进行装配 fileDTO.setFileName(fileName); //生成存储文件的路径 String savePath = this.getSavePath(directoryName); //根据生成存储文件的路径 生成对应文件夹 没有就新建 File directory = new File(savePath); if (!directory.exists()) { directory.mkdir(); } this.saveFile(file, savePath + fileName); fileDTO.setPath(FILE_SEPARATOR + directoryName + FILE_SEPARATOR + fileName); fileDTO.setFileSize(file.getSize()); return fileDTO; } public SystemFileDTO getFileInfo(MultipartFile file) { SystemFileDTO systemFileDTO = new SystemFileDTO(); //以下操作为 先取得传入文件的完整文件名 (文件名 + 后缀) 然后用FileUtil分别取出 文件名 和 不带 "." 的后缀 然后将这些内容装配进 实体中 //file.getOriginFilename 获取源文件 //FileUtil.getPrefix 返回主文件名 systemFileDTO.setFileName(FileUtil.getPrefix(file.getOriginalFilename())); return systemFileDTO; } public String createDirectory() { String directoryName = this.getDirectoryName(); String savePath = this.getSavePath(directoryName); File directory = new File(savePath); if (!directory.exists()) { directory.mkdir(); } return directoryName; } public void saveFile(MultipartFile file, String path) { try { file.transferTo(new File(path)); } catch (Exception e) { e.printStackTrace(); } } public String getTempPath(String fileName) { String tempPath = getStaticPath(COMMON_FILE) + FILE_SEPARATOR + "temp"; File file = new File(tempPath); if (!file.exists()) { file.mkdir(); } return tempPath + FILE_SEPARATOR + fileName; } public String getSavePath(String directoryName) { return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + directoryName + FILE_SEPARATOR; } public String getDirectory(String fileName) { return FILE_SEPARATOR + this.createDirectory() + FILE_SEPARATOR + fileName; } public String getDirectory2(String directoryName) { return FILE_SEPARATOR + directoryName + FILE_SEPARATOR; } public String getSystemPath(String url) { return getStaticPath(COMMON_FILE) + FILE_SEPARATOR + url; } public String getSystemPath() { return getStaticPath(COMMON_FILE); } public String getPath(String url) { return getStaticPath(COMMON_FILE) + url; } public static MultipartFile fileToMultipartFile(File file) { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(16, null); FileItem item = diskFileItemFactory.createItem(file.getName(), "text/plain", true, file.getName()); int bytesRead = 0; byte[] buffer = new byte[8192]; try { FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream(); int len = 8192; while ((bytesRead = fis.read(buffer, 0, len)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } return (MultipartFile) new CommonsMultipartFile(item); } public static File getFile(String url, String fileName) throws Exception { String name = ""; if (fileName.contains(".")) { name = fileName.substring(0, fileName.indexOf(".")); } //读取图片类型 String fileType = url.substring(url.lastIndexOf("."), url.length()); File file = null; URL urlfile; InputStream inStream = null; OutputStream os = null; try { file = File.createTempFile(name, fileType); //获取文件 urlfile = new URL(url); inStream = urlfile.openStream(); os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != os) { os.close(); } if (null != inStream) { inStream.close(); } } catch (Exception e) { e.printStackTrace(); } } return file; } public static File getFile1(String url, String fileName) throws Exception { String name = ""; if (fileName.contains(".")) { name = fileName.substring(0, fileName.indexOf(".")); } //读取图片类型 String fileType = url.substring(url.lastIndexOf("."), url.length()); File file = null; URL urlfile; InputStream inStream = null; OutputStream os = null; try { file = new File(name + fileType); //获取文件 urlfile = new URL(url); inStream = urlfile.openStream(); os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != os) { os.close(); } if (null != inStream) { inStream.close(); } } catch (Exception e) { e.printStackTrace(); } } return file; } public static File urlToFile(String fileUrl) { String path = System.getProperty("user.dir"); File tmpFile = new File(path, "tmp"); if (!tmpFile.exists()) { tmpFile.mkdirs(); } return urlToFile(fileUrl, tmpFile); } /** * @param fileUrl 资源地址 * @param tmpFile 临时文件 * @Description: 网络资源转file, 用完以后必须删除该临时文件 * @return: 返回值 */ public static File urlToFile(String fileUrl, File tmpFile) { String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")); FileOutputStream downloadFile = null; InputStream openStream = null; File savedFile = null; try { savedFile = new File(tmpFile.getAbsolutePath() + fileName); URL url = new URL(fileUrl); java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); openStream = connection.getInputStream(); int index; byte[] bytes = new byte[1024]; downloadFile = new FileOutputStream(savedFile); while ((index = openStream.read(bytes)) != -1) { downloadFile.write(bytes, 0, index); downloadFile.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (openStream != null) { openStream.close(); } if (downloadFile != null) { downloadFile.close(); } } catch (Exception e) { e.printStackTrace(); } } return savedFile; } public static MultipartFile urlToMultipartFile(String url, String fileName) throws Exception { File file = FileUtils.getFile1(url, fileName); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(16, null); FileItem item = diskFileItemFactory.createItem(file.getName(), "text/plain", true, file.getName()); int bytesRead = 0; byte[] buffer = new byte[8192]; try { FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream(); int len = 8192; while ((bytesRead = fis.read(buffer, 0, len)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } return new CommonsMultipartFile(item); } public UploadFileDTO uploadToLocal(String url, String type) throws Exception { MultipartFile file = FileUtils.urlToMultipartFile(url, type); UploadFileDTO fileDTO = fileUtils.uploadFile(file); return fileDTO; } public static String readerMethod() throws IOException { String ah = FileUtils.getStaticPath("setting.json"); File file = new File(ah); FileReader fileReader = new FileReader(file); Reader reader = new InputStreamReader(new FileInputStream(file), "Utf-8"); int ch = 0; StringBuffer sb = new StringBuffer(); while ((ch = reader.read()) != -1) { sb.append((char) ch); } fileReader.close(); reader.close(); String jsonStr = sb.toString(); return jsonStr; } public static File multipartFileToFile(MultipartFile file) throws Exception { File toFile = null; if (file.equals("") || file.getSize() <= 0) { file = null; } else { InputStream ins = null; ins = file.getInputStream(); toFile = new File(file.getOriginalFilename()); inputStreamToFile(ins, toFile); ins.close(); } return toFile; } //获取流文件 private static void inputStreamToFile(InputStream ins, File file) { try { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); } catch (Exception e) { e.printStackTrace(); } } public String getDirectoryName() { return DateUtils.getNowTimeFormat("yyyyMMdd"); } public static String getDateDirectoryName() { return DateUtils.getNowTimeFormat("yyyyMMdd"); } public static boolean deleteQuietly(final File file) { if (file == null) { return false; } try { if (file.isDirectory()) { cleanDirectory(file); } } catch (final Exception ignored) { } try { return file.delete(); } catch (final Exception ignored) { return false; } } public static void cleanDirectory(final File directory) throws IOException { final File[] files = verifiedListFiles(directory); IOException exception = null; for (final File file : files) { try { forceDelete(file); } catch (final IOException ioe) { exception = ioe; } } if (null != exception) { throw exception; } } private static File[] verifiedListFiles(final File directory) throws IOException { if (!directory.exists()) { final String message = directory + " does not exist"; throw new IllegalArgumentException(message); } if (!directory.isDirectory()) { final String message = directory + " is not a directory"; throw new IllegalArgumentException(message); } final File[] files = directory.listFiles(); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + directory); } return files; } public static void forceDelete(final File file) throws IOException { if (file.isDirectory()) { deleteDirectory(file); } else { final boolean filePresent = file.exists(); if (!file.delete()) { if (!filePresent) { throw new FileNotFoundException("File does not exist: " + file); } final String message = "Unable to delete file: " + file; throw new IOException(message); } } } public static void deleteDirectory(final File directory) throws IOException { if (!directory.exists()) { return; } if (!isSymlink(directory)) { cleanDirectory(directory); } if (!directory.delete()) { final String message = "Unable to delete directory " + directory + "."; throw new IOException(message); } } public static boolean isSymlink(final File file) throws IOException { if (file == null) { throw new NullPointerException("File must not be null"); } return Files.isSymbolicLink(file.toPath()); } public static String getFileExrName(String fileName) { if (fileName == null || fileName.trim().equals("")) { return ""; } String exrName = fileName.substring(fileName.indexOf("."), fileName.length()); return exrName; } public static String getDateFilePath(String path) { String directoryName = FileUtils.getDateDirectoryName(); String rePath = path + directoryName+"/"; return rePath; } }