From 30da249b6b87d21d2c7d5357adc9211e523ff2dd Mon Sep 17 00:00:00 2001
From: luqingjie <544309509@qq.com>
Date: Sat, 7 Mar 2026 13:34:04 +0800
Subject: [PATCH] 11
---
luqj-ec/pom.xml | 5 +
.../ec/controller/EcDeviceApiController.java | 18 +-
.../com/luqj/ec/service/IEcDeviceService.java | 2 +
.../ec/service/impl/EcDeviceServiceImpl.java | 53 +++---
luqj-javacv/pom.xml | 27 +++
.../java/com/luqj/javacv/utils/RtspUtil.java | 128 +++++++++++++
pom.xml | 1 +
ruoyi-admin/pom.xml | 5 +
.../src/main/resources/application.yml | 8 +-
.../com/ruoyi/common/config/RuoYiConfig.java | 84 +++++----
.../framework/config/SecurityConfig.java | 1 -
.../controller/FileUploadController.java | 89 +++++++++
.../system/service/IFileUploadService.java | 16 ++
.../service/impl/FileUploadServiceImpl.java | 172 ++++++++++++++++++
14 files changed, 540 insertions(+), 69 deletions(-)
create mode 100644 luqj-javacv/pom.xml
create mode 100644 luqj-javacv/src/main/java/com/luqj/javacv/utils/RtspUtil.java
create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/controller/FileUploadController.java
create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/IFileUploadService.java
create mode 100644 ruoyi-system/src/main/java/com/ruoyi/system/service/impl/FileUploadServiceImpl.java
diff --git a/luqj-ec/pom.xml b/luqj-ec/pom.xml
index 38d6948..3b3b72e 100644
--- a/luqj-ec/pom.xml
+++ b/luqj-ec/pom.xml
@@ -22,6 +22,11 @@
com.ruoyi
ruoyi-common
+
+ com.ruoyi
+ luqj-javacv
+ 3.4.0
+
com.baomidou
mybatis-plus-extension
diff --git a/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceApiController.java b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceApiController.java
index e822af1..80606a3 100644
--- a/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceApiController.java
+++ b/luqj-ec/src/main/java/com/luqj/ec/controller/EcDeviceApiController.java
@@ -1,15 +1,13 @@
package com.luqj.ec.controller;
+import com.luqj.ec.domain.EcDevice;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.luqj.ec.domain.dto.EcDeviceHeartbeatDto;
import com.luqj.ec.domain.dto.EcDeviceReportDto;
import com.luqj.ec.service.IEcDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ec/device-api")
@@ -26,7 +24,17 @@ public class EcDeviceApiController extends BaseController {
ecDeviceService.reportDevice(reportDto);
return AjaxResult.success("设备上报成功");
}
-
+ @GetMapping("/snapshop")
+ public AjaxResult snapshop(@RequestParam(name = "deviceCode") String deviceCode) {
+ EcDevice ecDevice = new EcDevice();
+ try {
+ ecDevice.setLastScreenPic(ecDeviceService.snapshop(deviceCode));
+ } catch (Exception e) {
+ logger.error(e.getMessage(),e);
+ return AjaxResult.error(e.getMessage());
+ }
+ return AjaxResult.success(ecDevice);
+ }
@PostMapping("/heartbeat")
public AjaxResult heartbeat(@RequestBody EcDeviceHeartbeatDto heartbeatDto) {
if (heartbeatDto.getDeviceCode() == null || heartbeatDto.getDeviceCode().isEmpty()) {
diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceService.java b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceService.java
index 7d5bab5..e08ea5e 100644
--- a/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceService.java
+++ b/luqj-ec/src/main/java/com/luqj/ec/service/IEcDeviceService.java
@@ -72,6 +72,8 @@ public interface IEcDeviceService extends IService {
EcDevicePlus getById(Long id, SFunction... columns);
+ String snapshop(String deviceCode) throws Exception;
+
Map getMapByIds(List ids, SFunction... columns);
List getByIds(List ids);
diff --git a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceServiceImpl.java b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceServiceImpl.java
index 6396e75..7263f63 100644
--- a/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceServiceImpl.java
+++ b/luqj-ec/src/main/java/com/luqj/ec/service/impl/EcDeviceServiceImpl.java
@@ -1,33 +1,29 @@
package com.luqj.ec.service.impl;
-import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
-import com.github.pagehelper.PageHelper;
-import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import com.ruoyi.common.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
-import java.util.List;
-import java.util.Map;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import com.luqj.ec.mapper.EcDeviceMapper;
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
+import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luqj.ec.domain.EcDevice;
import com.luqj.ec.domain.EcDevicePlus;
import com.luqj.ec.domain.dto.EcDeviceHeartbeatDto;
import com.luqj.ec.domain.dto.EcDeviceReportDto;
+import com.luqj.ec.mapper.EcDeviceMapper;
import com.luqj.ec.service.IEcDeviceService;
+import com.luqj.javacv.utils.RtspUtil;
+import com.ruoyi.common.config.RuoYiConfig;
+import com.ruoyi.common.select.SelectItem;
+import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
-import com.ruoyi.common.select.SelectItem;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+import java.util.*;
/**
* 设备(手机设备)Service业务层处理
- *
+ *
* @author luqj
* @date 2026-02-27
*/
@@ -37,6 +33,8 @@ public class EcDeviceServiceImpl extends ServiceImpl getByIds(List ids, SFunction... columns) {
@@ -61,6 +59,15 @@ public class EcDeviceServiceImpl extends ServiceImpl... columns) {
LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper()
@@ -141,7 +148,7 @@ public class EcDeviceServiceImpl extends ServiceImpl
+ 4.0.0
+
+ ruoyi
+ com.ruoyi
+ 3.4.0
+
+
+ luqj-javacv
+ jar
+
+ luqj-javacv
+ http://maven.apache.org
+
+
+ UTF-8
+
+
+
+
+ org.bytedeco
+ javacv-platform
+ 1.5.11
+
+
+
diff --git a/luqj-javacv/src/main/java/com/luqj/javacv/utils/RtspUtil.java b/luqj-javacv/src/main/java/com/luqj/javacv/utils/RtspUtil.java
new file mode 100644
index 0000000..c4994c1
--- /dev/null
+++ b/luqj-javacv/src/main/java/com/luqj/javacv/utils/RtspUtil.java
@@ -0,0 +1,128 @@
+package com.luqj.javacv.utils;
+
+import org.bytedeco.javacv.FFmpegFrameGrabber;
+import org.bytedeco.javacv.Frame;
+import org.bytedeco.javacv.Java2DFrameConverter;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.util.UUID;
+
+public class RtspUtil {
+ public static String screenshot(String rtspUrl, String basePath) throws Exception {
+ FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(rtspUrl);
+ // 🔑 等价于:-rtsp_transport tcp
+ grabber.setOption("rtsp_transport", "tcp");
+ // 降低首帧延迟
+ grabber.setOption("stimeout", "3000000"); // 3 秒
+ grabber.setOption("buffer_size", "1024000");
+ grabber.start();
+ Frame frame;
+ Java2DFrameConverter converter = new Java2DFrameConverter();
+ if (!basePath.endsWith("/")) {
+ basePath = basePath + "/";
+ }
+ String filename = uuid() + "_snapshot.jpg";
+ String savePathUrl = basePath + filename;
+ // 多抓几帧,避免黑屏
+ for (int i = 0; i < 10; i++) {
+ frame = grabber.grabImage();
+ if (frame != null) {
+ BufferedImage img = converter.getBufferedImage(frame);
+ ImageIO.write(img, "jpg", new File(savePathUrl));
+ break;
+ }
+ }
+ converter.close();
+ grabber.stop();
+ return filename;
+ }
+
+ public static byte[] screenshot(String rtspUrl) throws Exception {
+ FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(rtspUrl);
+ // 🔑 等价于:-rtsp_transport tcp
+ grabber.setOption("rtsp_transport", "tcp");
+ // 降低首帧延迟
+ grabber.setOption("stimeout", "3000000"); // 3 秒
+ grabber.setOption("buffer_size", "1024000");
+ grabber.start();
+ Frame frame;
+ Java2DFrameConverter converter = new Java2DFrameConverter();
+ byte[] bytes = new byte[0];
+ // 多抓几帧,避免黑屏
+ for (int i = 0; i < 10; i++) {
+ frame = grabber.grabImage();
+ if (frame != null) {
+ BufferedImage img = converter.getBufferedImage(frame);
+ // 如果你只想要 byte[](不落盘)
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ImageIO.write(img, "jpg", baos);
+ bytes = baos.toByteArray();
+ break;
+ }
+ }
+ converter.close();
+ grabber.stop();
+ return bytes;
+ }
+
+ public static String uuid() {
+ return UUID.randomUUID().toString().replaceAll("-", "");
+ }
+
+ public static boolean isStreamAvailable(String rtspUrl) {
+ FFmpegFrameGrabber grabber = null;
+ try {
+ grabber = new FFmpegFrameGrabber(rtspUrl);
+ grabber.setOption("rtsp_transport", "tcp");
+ grabber.setOption("stimeout", "5000000");
+ grabber.setOption("buffer_size", "1024000");
+ grabber.start();
+ for (int i = 0; i < 5; i++) {
+ Frame frame = grabber.grabImage();
+ if (frame != null) {
+ return true;
+ }
+ }
+ return false;
+ } catch (Exception e) {
+ return false;
+ } finally {
+ if (grabber != null) {
+ try {
+ grabber.stop();
+ } catch (Exception ignored) {
+ }
+ }
+ }
+ }
+
+ public static boolean isStreamAvailable(String rtspUrl, int timeoutMs) {
+ FFmpegFrameGrabber grabber = null;
+ try {
+ grabber = new FFmpegFrameGrabber(rtspUrl);
+ grabber.setOption("rtsp_transport", "tcp");
+ grabber.setOption("stimeout", String.valueOf(timeoutMs * 1000));
+ grabber.setOption("buffer_size", "1024000");
+ grabber.start();
+ for (int i = 0; i < 5; i++) {
+ Frame frame = grabber.grabImage();
+ if (frame != null) {
+ return true;
+ }
+ }
+ return false;
+ } catch (Exception e) {
+ return false;
+ } finally {
+ if (grabber != null) {
+ try {
+ grabber.stop();
+ } catch (Exception ignored) {
+ }
+ }
+ }
+ }
+}
diff --git a/pom.xml b/pom.xml
index b08f0d9..5c30d51 100644
--- a/pom.xml
+++ b/pom.xml
@@ -235,6 +235,7 @@
luqj-plugin-demo
luqj-djl
luqj-ec
+ luqj-javacv
pom
diff --git a/ruoyi-admin/pom.xml b/ruoyi-admin/pom.xml
index 26e8458..a21c526 100644
--- a/ruoyi-admin/pom.xml
+++ b/ruoyi-admin/pom.xml
@@ -24,6 +24,11 @@
+
+ com.ruoyi
+ luqj-javacv
+ 3.4.0
+
com.ruoyi
luqj-djl
diff --git a/ruoyi-admin/src/main/resources/application.yml b/ruoyi-admin/src/main/resources/application.yml
index da72c31..82d4cb5 100644
--- a/ruoyi-admin/src/main/resources/application.yml
+++ b/ruoyi-admin/src/main/resources/application.yml
@@ -4,6 +4,11 @@ ruoyi:
- /demo/index
- /system/demoUsdt/**
- /system/test/testPlugin
+ - /system/file/upload
+ - /system/file/uploads
+ - /system/file/uploadImage
+ - /ec/device-api/report
+ - /ec/device-api/heartbeat
# 名称
name: RuoYi
# 版本
@@ -12,6 +17,8 @@ ruoyi:
copyrightYear: 2021
# 实例演示开关
demoEnabled: true
+ reqUrl: http://192.168.3.199:2020/profile
+ #http://127.0.0.1:2020/profile/upload/2024/05/15/1.jpeg
# 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)
profile: D:/ruoyi/uploadPath
# 获取ip地址开关
@@ -134,7 +141,6 @@ mybatis-plus:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapper/**/*Mapper.xml
global-config:
- identifier-generator: com.ruoyi.framework.config.CustomKeyGenerator
db-config:
id-type: auto
logic-not-delete-value: 1
diff --git a/ruoyi-common/src/main/java/com/ruoyi/common/config/RuoYiConfig.java b/ruoyi-common/src/main/java/com/ruoyi/common/config/RuoYiConfig.java
index d5d8723..d9c01c0 100644
--- a/ruoyi-common/src/main/java/com/ruoyi/common/config/RuoYiConfig.java
+++ b/ruoyi-common/src/main/java/com/ruoyi/common/config/RuoYiConfig.java
@@ -5,112 +5,118 @@ import org.springframework.stereotype.Component;
/**
* 读取项目相关配置
- *
+ *
* @author ruoyi
*/
@Component
@ConfigurationProperties(prefix = "ruoyi")
-public class RuoYiConfig
-{
- /** 项目名称 */
+public class RuoYiConfig {
+ /**
+ * 项目名称
+ */
private String name;
- /** 版本 */
+ /**
+ * 版本
+ */
private String version;
- /** 版权年份 */
+ /**
+ * 版权年份
+ */
private String copyrightYear;
- /** 实例演示开关 */
+ /**
+ * 实例演示开关
+ */
private boolean demoEnabled;
- /** 上传路径 */
+ private String reqUrl;
+
+ /**
+ * 上传路径
+ */
private static String profile;
- /** 获取地址开关 */
+ /**
+ * 获取地址开关
+ */
private static boolean addressEnabled;
- public String getName()
- {
+ public String getName() {
return name;
}
- public void setName(String name)
- {
+ public void setReqUrl(String url) {
+ reqUrl = url;
+ }
+
+ public void setName(String name) {
this.name = name;
}
- public String getVersion()
- {
+ public String getReqUrl() {
+ return reqUrl;
+ }
+
+ public String getVersion() {
return version;
}
- public void setVersion(String version)
- {
+ public void setVersion(String version) {
this.version = version;
}
- public String getCopyrightYear()
- {
+ public String getCopyrightYear() {
return copyrightYear;
}
- public void setCopyrightYear(String copyrightYear)
- {
+ public void setCopyrightYear(String copyrightYear) {
this.copyrightYear = copyrightYear;
}
- public boolean isDemoEnabled()
- {
+ public boolean isDemoEnabled() {
return demoEnabled;
}
- public void setDemoEnabled(boolean demoEnabled)
- {
+ public void setDemoEnabled(boolean demoEnabled) {
this.demoEnabled = demoEnabled;
}
- public static String getProfile()
- {
+ public static String getProfile() {
return profile;
}
- public void setProfile(String profile)
- {
+ public void setProfile(String profile) {
RuoYiConfig.profile = profile;
}
- public static boolean isAddressEnabled()
- {
+ public static boolean isAddressEnabled() {
return addressEnabled;
}
- public void setAddressEnabled(boolean addressEnabled)
- {
+ public void setAddressEnabled(boolean addressEnabled) {
RuoYiConfig.addressEnabled = addressEnabled;
}
/**
* 获取头像上传路径
*/
- public static String getAvatarPath()
- {
+ public static String getAvatarPath() {
return getProfile() + "/avatar";
}
/**
* 获取下载路径
*/
- public static String getDownloadPath()
- {
+ public static String getDownloadPath() {
return getProfile() + "/download/";
}
/**
* 获取上传路径
*/
- public static String getUploadPath()
- {
+ public static String getUploadPath() {
return getProfile() + "/upload";
}
}
diff --git a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
index 88c8a8e..d47d739 100644
--- a/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
+++ b/ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
@@ -128,7 +128,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/life/housingEstate/all-by-letter").permitAll()
.antMatchers("/system/config/getVerifyStatus").permitAll()
.antMatchers("/system/config/setVerifyStatus").permitAll()
- .antMatchers("/ec/device-api/**").anonymous()
.anyRequest().authenticated()
.and()
.headers().frameOptions().disable();
diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/controller/FileUploadController.java b/ruoyi-system/src/main/java/com/ruoyi/system/controller/FileUploadController.java
new file mode 100644
index 0000000..0dddda5
--- /dev/null
+++ b/ruoyi-system/src/main/java/com/ruoyi/system/controller/FileUploadController.java
@@ -0,0 +1,89 @@
+package com.ruoyi.system.controller;
+
+import com.ruoyi.common.core.domain.AjaxResult;
+import com.ruoyi.system.service.IFileUploadService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.util.List;
+
+@RestController
+@RequestMapping("/system/file")
+public class FileUploadController {
+
+ @Autowired
+ private IFileUploadService fileUploadService;
+
+ @PostMapping("/upload")
+ public AjaxResult uploadFile(@RequestParam("file") MultipartFile file,
+ @RequestParam(value = "module", required = false, defaultValue = "common") String module) {
+ try {
+ String url = fileUploadService.uploadFile(file, module);
+ AjaxResult ajax = AjaxResult.success();
+ ajax.put("url", url);
+ ajax.put("fileName", file.getOriginalFilename());
+ return ajax;
+ } catch (Exception e) {
+ return AjaxResult.error(e.getMessage());
+ }
+ }
+
+ @PostMapping("/uploads")
+ public AjaxResult uploadFiles(@RequestParam("files") List files,
+ @RequestParam(value = "module", required = false, defaultValue = "common") String module) {
+ try {
+ List urls = fileUploadService.uploadFiles(files, module);
+ AjaxResult ajax = AjaxResult.success();
+ ajax.put("urls", urls);
+ ajax.put("count", urls.size());
+ return ajax;
+ } catch (Exception e) {
+ return AjaxResult.error(e.getMessage());
+ }
+ }
+
+ @PostMapping("/uploadImage")
+ public AjaxResult uploadImage(@RequestParam("file") MultipartFile file,
+ @RequestParam(value = "module", required = false, defaultValue = "image") String module) {
+ try {
+ String originalFilename = file.getOriginalFilename();
+ if (originalFilename != null) {
+ String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
+ String[] allowedExtensions = {"png", "jpg", "jpeg", "gif", "bmp", "webp"};
+ boolean isImage = false;
+ for (String allowed : allowedExtensions) {
+ if (allowed.equalsIgnoreCase(extension)) {
+ isImage = true;
+ break;
+ }
+ }
+ if (!isImage) {
+ return AjaxResult.error("只允许上传图片文件(png, jpg, jpeg, gif, bmp, webp)");
+ }
+ }
+
+ String url = fileUploadService.uploadFile(file, module);
+ AjaxResult ajax = AjaxResult.success();
+ ajax.put("url", url);
+ ajax.put("fileName", file.getOriginalFilename());
+ return ajax;
+ } catch (Exception e) {
+ return AjaxResult.error(e.getMessage());
+ }
+ }
+
+ @DeleteMapping("/delete")
+ public AjaxResult deleteFile(@RequestParam("filePath") String filePath) {
+ try {
+ boolean result = fileUploadService.deleteFile(filePath);
+ if (result) {
+ return AjaxResult.success("删除成功");
+ } else {
+ return AjaxResult.error("删除失败,文件不存在或已被删除");
+ }
+ } catch (Exception e) {
+ return AjaxResult.error(e.getMessage());
+ }
+ }
+}
diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/IFileUploadService.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/IFileUploadService.java
new file mode 100644
index 0000000..eceb499
--- /dev/null
+++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/IFileUploadService.java
@@ -0,0 +1,16 @@
+package com.ruoyi.system.service;
+
+import org.springframework.web.multipart.MultipartFile;
+
+import java.util.List;
+
+public interface IFileUploadService {
+
+ String uploadFile(MultipartFile file, String module);
+
+ List uploadFiles(List files, String module);
+
+ boolean deleteFile(String filePath);
+
+ String getFileUrl(String filePath);
+}
diff --git a/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/FileUploadServiceImpl.java b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/FileUploadServiceImpl.java
new file mode 100644
index 0000000..8888b59
--- /dev/null
+++ b/ruoyi-system/src/main/java/com/ruoyi/system/service/impl/FileUploadServiceImpl.java
@@ -0,0 +1,172 @@
+package com.ruoyi.system.service.impl;
+
+import com.ruoyi.common.config.RuoYiConfig;
+import com.ruoyi.common.constant.Constants;
+import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
+import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
+import com.ruoyi.common.exception.file.InvalidExtensionException;
+import com.ruoyi.common.utils.DateUtils;
+import com.ruoyi.common.utils.StringUtils;
+import com.ruoyi.common.utils.file.MimeTypeUtils;
+import com.ruoyi.common.utils.uuid.IdUtils;
+import com.ruoyi.system.service.IFileUploadService;
+import org.apache.commons.io.FilenameUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+@Service
+public class FileUploadServiceImpl implements IFileUploadService {
+
+ private static final Logger log = LoggerFactory.getLogger(FileUploadServiceImpl.class);
+
+ private static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
+
+ private static final int DEFAULT_FILE_NAME_LENGTH = 100;
+
+ private static final String[] DEFAULT_ALLOWED_EXTENSION = {
+ "png", "jpg", "jpeg", "gif", "bmp", "webp",
+ "doc", "docx", "xls", "xlsx", "ppt", "pptx",
+ "pdf", "txt", "zip", "rar", "7z",
+ "mp4", "avi", "mov", "wmv", "flv", "mp3", "wav"
+ };
+
+ @Override
+ public String uploadFile(MultipartFile file, String module) {
+ try {
+ String baseDir = getUploadPath(module);
+ return upload(baseDir, file, DEFAULT_ALLOWED_EXTENSION);
+ } catch (Exception e) {
+ log.error("文件上传失败: {}", e.getMessage(), e);
+ throw new RuntimeException("文件上传失败: " + e.getMessage());
+ }
+ }
+
+ @Override
+ public List uploadFiles(List files, String module) {
+ List urls = new ArrayList<>();
+ for (MultipartFile file : files) {
+ if (!file.isEmpty()) {
+ String url = uploadFile(file, module);
+ urls.add(url);
+ }
+ }
+ return urls;
+ }
+
+ @Override
+ public boolean deleteFile(String filePath) {
+ if (StringUtils.isEmpty(filePath)) {
+ return false;
+ }
+ try {
+ String localPath = RuoYiConfig.getProfile();
+ String fullPath = localPath + StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX);
+ File file = new File(fullPath);
+ if (file.exists()) {
+ return file.delete();
+ }
+ } catch (Exception e) {
+ log.error("删除文件失败: {}", e.getMessage(), e);
+ }
+ return false;
+ }
+
+ @Override
+ public String getFileUrl(String filePath) {
+ if (StringUtils.isEmpty(filePath)) {
+ return "";
+ }
+ if (filePath.startsWith(Constants.RESOURCE_PREFIX)) {
+ return filePath;
+ }
+ return Constants.RESOURCE_PREFIX + "/" + filePath;
+ }
+
+ private String getUploadPath(String module) {
+ String basePath = RuoYiConfig.getUploadPath();
+ if (StringUtils.isNotEmpty(module)) {
+ return basePath + File.separator + module;
+ }
+ return basePath;
+ }
+
+ private String upload(String baseDir, MultipartFile file, String[] allowedExtension)
+ throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
+ InvalidExtensionException {
+ int fileNamelength = file.getOriginalFilename().length();
+ if (fileNamelength > DEFAULT_FILE_NAME_LENGTH) {
+ throw new FileNameLengthLimitExceededException(DEFAULT_FILE_NAME_LENGTH);
+ }
+
+ assertAllowed(file, allowedExtension);
+
+ String fileName = extractFilename(file);
+
+ File desc = getAbsoluteFile(baseDir, fileName);
+ file.transferTo(desc);
+
+ String pathFileName = getPathFileName(baseDir, fileName);
+ return pathFileName;
+ }
+
+ private String extractFilename(MultipartFile file) {
+ String extension = getExtension(file);
+ return DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
+ }
+
+ private File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
+ File desc = new File(uploadDir + File.separator + fileName);
+
+ if (!desc.getParentFile().exists()) {
+ desc.getParentFile().mkdirs();
+ }
+ if (!desc.exists()) {
+ desc.createNewFile();
+ }
+ return desc;
+ }
+
+ private String getPathFileName(String uploadDir, String fileName) throws IOException {
+ int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
+ String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
+ return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
+ }
+
+ private void assertAllowed(MultipartFile file, String[] allowedExtension)
+ throws FileSizeLimitExceededException, InvalidExtensionException {
+ long size = file.getSize();
+ if (size > DEFAULT_MAX_SIZE) {
+ throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
+ }
+
+ String fileName = file.getOriginalFilename();
+ String extension = getExtension(file);
+ if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
+ throw new InvalidExtensionException(allowedExtension, extension, fileName);
+ }
+ }
+
+ private boolean isAllowedExtension(String extension, String[] allowedExtension) {
+ for (String str : allowedExtension) {
+ if (str.equalsIgnoreCase(extension)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private String getExtension(MultipartFile file) {
+ String extension = FilenameUtils.getExtension(file.getOriginalFilename());
+ if (StringUtils.isEmpty(extension)) {
+ extension = MimeTypeUtils.getExtension(file.getContentType());
+ }
+ return extension;
+ }
+}