FileUtils.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. package com.ruoyi.common.utils.file;
  2. import com.ruoyi.common.config.RuoYiConfig;
  3. import com.ruoyi.common.utils.DateUtils;
  4. import com.ruoyi.common.utils.StringUtils;
  5. import com.ruoyi.common.utils.uuid.IdUtils;
  6. import net.coobird.thumbnailator.Thumbnails;
  7. import org.apache.commons.fileupload.disk.DiskFileItem;
  8. import org.apache.commons.io.FilenameUtils;
  9. import org.apache.commons.io.IOUtils;
  10. import org.apache.commons.lang3.ArrayUtils;
  11. import org.apache.tika.Tika;
  12. import org.springframework.mock.web.MockMultipartFile;
  13. import org.springframework.web.multipart.MultipartFile;
  14. import org.springframework.web.multipart.commons.CommonsMultipartFile;
  15. import javax.servlet.http.HttpServletRequest;
  16. import javax.servlet.http.HttpServletResponse;
  17. import java.io.*;
  18. import java.net.URL;
  19. import java.net.URLEncoder;
  20. import java.nio.charset.StandardCharsets;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. /**
  24. * 文件处理工具类
  25. *
  26. * @author ruoyi
  27. */
  28. public class FileUtils {
  29. public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
  30. /**
  31. * 输出指定文件的byte数组
  32. *
  33. * @param filePath 文件路径
  34. * @param os 输出流
  35. * @return
  36. */
  37. public static void writeBytes(String filePath, OutputStream os) throws IOException {
  38. FileInputStream fis = null;
  39. try {
  40. File file = new File(filePath);
  41. if (!file.exists()) {
  42. throw new FileNotFoundException(filePath);
  43. }
  44. fis = new FileInputStream(file);
  45. byte[] b = new byte[1024];
  46. int length;
  47. while ((length = fis.read(b)) > 0) {
  48. os.write(b, 0, length);
  49. }
  50. } catch (IOException e) {
  51. throw e;
  52. } finally {
  53. IOUtils.close(os);
  54. IOUtils.close(fis);
  55. }
  56. }
  57. /**
  58. * 写数据到文件中
  59. *
  60. * @param data 数据
  61. * @return 目标文件
  62. * @throws IOException IO异常
  63. */
  64. public static String writeImportBytes(byte[] data) throws IOException {
  65. return writeBytes(data, RuoYiConfig.getImportPath());
  66. }
  67. /**
  68. * 写数据到文件中
  69. *
  70. * @param data 数据
  71. * @param uploadDir 目标文件
  72. * @return 目标文件
  73. * @throws IOException IO异常
  74. */
  75. public static String writeBytes(byte[] data, String uploadDir) throws IOException {
  76. FileOutputStream fos = null;
  77. String pathName = "";
  78. try {
  79. String extension = getFileExtendName(data);
  80. pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
  81. File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
  82. fos = new FileOutputStream(file);
  83. fos.write(data);
  84. } finally {
  85. IOUtils.close(fos);
  86. }
  87. return FileUploadUtils.getPathFileName(uploadDir, pathName);
  88. }
  89. /**
  90. * 删除文件
  91. *
  92. * @param filePath 文件
  93. * @return
  94. */
  95. public static boolean deleteFile(String filePath) {
  96. boolean flag = false;
  97. File file = new File(filePath);
  98. // 路径为文件且不为空则进行删除
  99. if (file.isFile() && file.exists()) {
  100. flag = file.delete();
  101. }
  102. return flag;
  103. }
  104. /**
  105. * 文件名称验证
  106. *
  107. * @param filename 文件名称
  108. * @return true 正常 false 非法
  109. */
  110. public static boolean isValidFilename(String filename) {
  111. return filename.matches(FILENAME_PATTERN);
  112. }
  113. /**
  114. * 检查文件是否可下载
  115. *
  116. * @param resource 需要下载的文件
  117. * @return true 正常 false 非法
  118. */
  119. public static boolean checkAllowDownload(String resource) {
  120. // 禁止目录上跳级别
  121. if (StringUtils.contains(resource, "..")) {
  122. return false;
  123. }
  124. // 检查允许下载的文件规则
  125. if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) {
  126. return true;
  127. }
  128. // 不在允许下载的文件规则
  129. return false;
  130. }
  131. /**
  132. * 下载文件名重新编码
  133. *
  134. * @param request 请求对象
  135. * @param fileName 文件名
  136. * @return 编码后的文件名
  137. */
  138. public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
  139. final String agent = request.getHeader("USER-AGENT");
  140. String filename = fileName;
  141. if (agent.contains("MSIE")) {
  142. // IE浏览器
  143. filename = URLEncoder.encode(filename, "utf-8");
  144. filename = filename.replace("+", " ");
  145. } else if (agent.contains("Firefox")) {
  146. // 火狐浏览器
  147. filename = new String(fileName.getBytes(), "ISO8859-1");
  148. } else if (agent.contains("Chrome")) {
  149. // google浏览器
  150. filename = URLEncoder.encode(filename, "utf-8");
  151. } else {
  152. // 其它浏览器
  153. filename = URLEncoder.encode(filename, "utf-8");
  154. }
  155. return filename;
  156. }
  157. /**
  158. * 下载文件名重新编码
  159. *
  160. * @param response 响应对象
  161. * @param realFileName 真实文件名
  162. */
  163. public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
  164. String percentEncodedFileName = percentEncode(realFileName);
  165. StringBuilder contentDispositionValue = new StringBuilder();
  166. contentDispositionValue.append("attachment; filename=")
  167. .append(percentEncodedFileName)
  168. .append(";")
  169. .append("filename*=")
  170. .append("utf-8''")
  171. .append(percentEncodedFileName);
  172. response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
  173. response.setHeader("Content-disposition", contentDispositionValue.toString());
  174. response.setHeader("download-filename", percentEncodedFileName);
  175. }
  176. /**
  177. * 百分号编码工具方法
  178. *
  179. * @param s 需要百分号编码的字符串
  180. * @return 百分号编码后的字符串
  181. */
  182. public static String percentEncode(String s) throws UnsupportedEncodingException {
  183. String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
  184. return encode.replaceAll("\\+", "%20");
  185. }
  186. /**
  187. * 获取图像后缀
  188. *
  189. * @param photoByte 图像数据
  190. * @return 后缀名
  191. */
  192. public static String getFileExtendName(byte[] photoByte) {
  193. String strFileExtendName = "jpg";
  194. if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
  195. && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
  196. strFileExtendName = "gif";
  197. } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
  198. strFileExtendName = "jpg";
  199. } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
  200. strFileExtendName = "bmp";
  201. } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
  202. strFileExtendName = "png";
  203. }
  204. return strFileExtendName;
  205. }
  206. /**
  207. * 获取文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi.png
  208. *
  209. * @param fileName 路径名称
  210. * @return 没有文件路径的名称
  211. */
  212. public static String getName(String fileName) {
  213. if (fileName == null) {
  214. return null;
  215. }
  216. int lastUnixPos = fileName.lastIndexOf('/');
  217. int lastWindowsPos = fileName.lastIndexOf('\\');
  218. int index = Math.max(lastUnixPos, lastWindowsPos);
  219. return fileName.substring(index + 1);
  220. }
  221. /**
  222. * 获取不带后缀文件名称 /profile/upload/2022/04/16/ruoyi.png -- ruoyi
  223. *
  224. * @param fileName 路径名称
  225. * @return 没有文件路径和后缀的名称
  226. */
  227. public static String getNameNotSuffix(String fileName) {
  228. if (fileName == null) {
  229. return null;
  230. }
  231. String baseName = FilenameUtils.getBaseName(fileName);
  232. return baseName;
  233. }
  234. /**
  235. * 区分上传的文件是什么类型
  236. *
  237. * @param file 文件流
  238. * @return 类型
  239. */
  240. public static String getFileType(MultipartFile file) {
  241. Tika tika = new Tika();
  242. try {
  243. String mimeType = tika.detect(file.getInputStream());
  244. if (mimeType.startsWith("image/")) {
  245. return "image";
  246. } else if (mimeType.startsWith("audio/")) {
  247. return "audio";
  248. } else if (mimeType.startsWith("video/")) {
  249. return "video";
  250. } else {
  251. return "other";
  252. }
  253. } catch (IOException e) {
  254. e.printStackTrace();
  255. return "other";
  256. }
  257. }
  258. /**
  259. * 获取文件类型(图片、音频、视频等)
  260. *
  261. * @param fileUrl 文件的URL
  262. * @return 文件类型
  263. */
  264. public static String getFileTypeFromUrl(String fileUrl) throws IOException {
  265. URL url = new URL(fileUrl);
  266. // 设置连接属性
  267. java.net.HttpURLConnection connection = null;
  268. try {
  269. // 检查是否需要设置代理
  270. String proxyHost = System.getProperty("http.proxyHost");
  271. String proxyPort = System.getProperty("http.proxyPort");
  272. if (StringUtils.isNotEmpty(proxyHost) && StringUtils.isNotEmpty(proxyPort)) {
  273. // 使用系统配置的代理
  274. java.net.Proxy proxy = new java.net.Proxy(
  275. java.net.Proxy.Type.HTTP,
  276. new java.net.InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))
  277. );
  278. connection = (java.net.HttpURLConnection) url.openConnection(proxy);
  279. } else {
  280. connection = (java.net.HttpURLConnection) url.openConnection();
  281. }
  282. // 设置连接参数
  283. connection.setConnectTimeout(5000); // 5秒连接超时
  284. connection.setReadTimeout(5000); // 5秒读取超时
  285. connection.setRequestMethod("GET");
  286. connection.setDoInput(true);
  287. // 尝试连接
  288. connection.connect();
  289. try (InputStream inputStream = connection.getInputStream()) {
  290. Tika tika = new Tika();
  291. String mimeType = tika.detect(inputStream);
  292. if (mimeType.startsWith("image/")) {
  293. return "image";
  294. } else if (mimeType.startsWith("audio/")) {
  295. return "audio";
  296. } else if (mimeType.startsWith("video/")) {
  297. return "video";
  298. } else {
  299. return "other";
  300. }
  301. }
  302. } catch (java.net.SocketException e) {
  303. // 处理网络权限错误
  304. System.err.println("网络连接权限被拒绝: " + e.getMessage());
  305. // 尝试从URL路径推断文件类型
  306. String path = url.getPath();
  307. String extension = FilenameUtils.getExtension(path).toLowerCase();
  308. // 根据扩展名判断文件类型
  309. if (MimeTypeUtils.isImage(extension)) {
  310. return "image";
  311. } else if (MimeTypeUtils.isAudio(extension)) {
  312. return "audio";
  313. } else if (MimeTypeUtils.isVideo(extension)) {
  314. return "video";
  315. } else {
  316. return "other";
  317. }
  318. } finally {
  319. if (connection != null) {
  320. connection.disconnect();
  321. }
  322. }
  323. }
  324. /**
  325. * 截取视频的指定时间帧,生成图片文件
  326. *
  327. * @param source 源文件
  328. * @param file 图片文件
  329. * @param time 截图时间 HH:mm:ss.[SSS]
  330. * @throws IOException
  331. * @throws InterruptedException
  332. */
  333. public static boolean screenShots(String source, String file, String time) throws IOException, InterruptedException {
  334. List<String> commands = new ArrayList<>();
  335. commands.add("ffmpeg");
  336. commands.add("-i");
  337. commands.add(source);
  338. commands.add("-ss");
  339. commands.add(time);
  340. commands.add("-y");
  341. commands.add("-q:v");
  342. commands.add("1");
  343. commands.add("-frames:v");
  344. commands.add("1");
  345. commands.add("-f");
  346. commands.add("image2");
  347. commands.add(file);
  348. Process process = new ProcessBuilder(commands).start();
  349. // 读取进程标准输出
  350. new Thread(() -> {
  351. try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
  352. String line = null;
  353. while ((line = bufferedReader.readLine()) != null) {
  354. System.out.println(line);
  355. }
  356. } catch (IOException e) {
  357. }
  358. }).start();
  359. // 读取进程异常输出
  360. new Thread(() -> {
  361. try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
  362. String line = null;
  363. while ((line = bufferedReader.readLine()) != null) {
  364. System.out.println(line);
  365. }
  366. } catch (IOException e) {
  367. }
  368. }).start();
  369. if (process.waitFor() != 0) {
  370. return false;
  371. }
  372. OssUtils.uploadFile(file);
  373. return true;
  374. }
  375. /**
  376. * File转换MultipartFile
  377. *
  378. * @param file 文件
  379. * @return MultipartFile
  380. * @throws Exception 异常
  381. */
  382. public static MultipartFile convertFileToMultipartFile(File file) throws Exception {
  383. DiskFileItem fileItem = new DiskFileItem("file", "image/jpg", true, file.getName(), (int) file.length(), file.getParentFile());
  384. try (FileInputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
  385. IOUtils.copy(input, os);
  386. }
  387. return new CommonsMultipartFile(fileItem);
  388. }
  389. public static MultipartFile convertToJpg(MultipartFile file) throws IOException {
  390. byte[] bytes = file.getBytes();
  391. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  392. Thumbnails.of(new ByteArrayInputStream(bytes))
  393. .scale(1)
  394. .outputFormat("jpg")
  395. .toOutputStream(outputStream);
  396. return new MockMultipartFile(
  397. file.getName(),
  398. file.getOriginalFilename().replaceAll("\\.[^.]+$", ".jpg"),
  399. "image/jpeg",
  400. outputStream.toByteArray()
  401. );
  402. }
  403. /**
  404. * 清理临时文件
  405. *
  406. * @param fileName 文件名称
  407. */
  408. public static void cleanTempDir(String fileName) {
  409. String tempDirPath = System.getProperty("java.io.tmpdir");
  410. File tempDir = new File(tempDirPath);
  411. if (tempDir.exists() && tempDir.isDirectory()) {
  412. File[] files = tempDir.listFiles();
  413. if (files != null) {
  414. for (File file : files) {
  415. // 检查是否是临时文件,并尝试删除
  416. if (file.isFile() && file.getName().endsWith(".tmp") || file.getName().startsWith(fileName)) {
  417. boolean deleted = file.delete();
  418. if (deleted) {
  419. System.out.println("删除临时文件成功: " + file.getName());
  420. } else {
  421. System.out.println("删除临时文件失败: " + file.getName());
  422. }
  423. }
  424. }
  425. }
  426. }
  427. }
  428. }