This commit is contained in:
lu7213 committed 2026-03-07 13:34:04 +08:00
1 parent 6c73388fdd
commit 30da249b6b
14 files changed
+532 -61

No files matched your search

+5
View File
@@ -22,6 +22,11 @@
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
<artifactId>ruoyi-common</artifactId> <artifactId>ruoyi-common</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>luqj-javacv</artifactId>
<version>3.4.0</version>
</dependency>
<dependency> <dependency>
<groupId>com.baomidou</groupId> <groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId> <artifactId>mybatis-plus-extension</artifactId>
@@ -1,15 +1,13 @@
package com.luqj.ec.controller; package com.luqj.ec.controller;
import com.luqj.ec.domain.EcDevice;
import com.ruoyi.common.core.controller.BaseController; import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.common.core.domain.AjaxResult;
import com.luqj.ec.domain.dto.EcDeviceHeartbeatDto; import com.luqj.ec.domain.dto.EcDeviceHeartbeatDto;
import com.luqj.ec.domain.dto.EcDeviceReportDto; import com.luqj.ec.domain.dto.EcDeviceReportDto;
import com.luqj.ec.service.IEcDeviceService; import com.luqj.ec.service.IEcDeviceService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
@RequestMapping("/ec/device-api") @RequestMapping("/ec/device-api")
@@ -26,7 +24,17 @@ public class EcDeviceApiController extends BaseController {
ecDeviceService.reportDevice(reportDto); ecDeviceService.reportDevice(reportDto);
return AjaxResult.success("设备上报成功"); 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") @PostMapping("/heartbeat")
public AjaxResult heartbeat(@RequestBody EcDeviceHeartbeatDto heartbeatDto) { public AjaxResult heartbeat(@RequestBody EcDeviceHeartbeatDto heartbeatDto) {
if (heartbeatDto.getDeviceCode() == null || heartbeatDto.getDeviceCode().isEmpty()) { if (heartbeatDto.getDeviceCode() == null || heartbeatDto.getDeviceCode().isEmpty()) {
@@ -72,6 +72,8 @@ public interface IEcDeviceService extends IService<EcDevicePlus> {
EcDevicePlus getById(Long id, SFunction<EcDevicePlus, ?>... columns); EcDevicePlus getById(Long id, SFunction<EcDevicePlus, ?>... columns);
String snapshop(String deviceCode) throws Exception;
Map<Long, EcDevicePlus> getMapByIds(List<Long> ids, SFunction<EcDevicePlus, ?>... columns); Map<Long, EcDevicePlus> getMapByIds(List<Long> ids, SFunction<EcDevicePlus, ?>... columns);
List<EcDevicePlus> getByIds(List<Long> ids); List<EcDevicePlus> getByIds(List<Long> ids);
@@ -1,29 +1,25 @@
package com.luqj.ec.service.impl; 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 com.alibaba.fastjson.JSONArray;
import java.util.List; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.Map; import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.springframework.beans.factory.annotation.Autowired; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.luqj.ec.mapper.EcDeviceMapper;
import com.luqj.ec.domain.EcDevice; import com.luqj.ec.domain.EcDevice;
import com.luqj.ec.domain.EcDevicePlus; import com.luqj.ec.domain.EcDevicePlus;
import com.luqj.ec.domain.dto.EcDeviceHeartbeatDto; import com.luqj.ec.domain.dto.EcDeviceHeartbeatDto;
import com.luqj.ec.domain.dto.EcDeviceReportDto; import com.luqj.ec.domain.dto.EcDeviceReportDto;
import com.luqj.ec.mapper.EcDeviceMapper;
import com.luqj.ec.service.IEcDeviceService; 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.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate; 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业务层处理 * 设备(手机设备)Service业务层处理
@@ -37,6 +33,8 @@ public class EcDeviceServiceImpl extends ServiceImpl<EcDeviceMapper, EcDevicePlu
private EcDeviceMapper ecDeviceMapper; private EcDeviceMapper ecDeviceMapper;
@Autowired @Autowired
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
@Autowired
private RuoYiConfig ruoYiConfig;
@Override @Override
public List<EcDevicePlus> getByIds(List<Long> ids, SFunction<EcDevicePlus, ?>... columns) { public List<EcDevicePlus> getByIds(List<Long> ids, SFunction<EcDevicePlus, ?>... columns) {
@@ -61,6 +59,15 @@ public class EcDeviceServiceImpl extends ServiceImpl<EcDeviceMapper, EcDevicePlu
return result; return result;
} }
public String snapshop(String deviceCode) throws Exception {
File file = new File(RuoYiConfig.getProfile() + "/ec/" + deviceCode + "/");
if (!file.exists()) {
file.mkdirs();
}
String fileName = RtspUtil.screenshot("rtsp://192.168.3.186:554/live/" + deviceCode, RuoYiConfig.getProfile() + "/ec/" + deviceCode + "/");
return ruoYiConfig.getReqUrl() + "/ec/" + deviceCode + "/" + fileName;
}
@Override @Override
public EcDevicePlus getById(Long id, SFunction<EcDevicePlus, ?>... columns) { public EcDevicePlus getById(Long id, SFunction<EcDevicePlus, ?>... columns) {
LambdaQueryWrapper<EcDevicePlus> lambdaQueryWrapper = new LambdaQueryWrapper<EcDevicePlus>() LambdaQueryWrapper<EcDevicePlus> lambdaQueryWrapper = new LambdaQueryWrapper<EcDevicePlus>()
+27
View File
@@ -0,0 +1,27 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>ruoyi</artifactId>
<groupId>com.ruoyi</groupId>
<version>3.4.0</version>
</parent>
<artifactId>luqj-javacv</artifactId>
<packaging>jar</packaging>
<name>luqj-javacv</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.11</version>
</dependency>
</dependencies>
</project>
@@ -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) {
}
}
}
}
}
+1
View File
@@ -235,6 +235,7 @@
<module>luqj-plugin-demo</module> <module>luqj-plugin-demo</module>
<module>luqj-djl</module> <module>luqj-djl</module>
<module>luqj-ec</module> <module>luqj-ec</module>
<module>luqj-javacv</module>
</modules> </modules>
<packaging>pom</packaging> <packaging>pom</packaging>
+5
View File
@@ -24,6 +24,11 @@
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>
<dependencies> <dependencies>
<dependency>
<groupId>com.ruoyi</groupId>
<artifactId>luqj-javacv</artifactId>
<version>3.4.0</version>
</dependency>
<dependency> <dependency>
<groupId>com.ruoyi</groupId> <groupId>com.ruoyi</groupId>
<artifactId>luqj-djl</artifactId> <artifactId>luqj-djl</artifactId>
@@ -4,6 +4,11 @@ ruoyi:
- /demo/index - /demo/index
- /system/demoUsdt/** - /system/demoUsdt/**
- /system/test/testPlugin - /system/test/testPlugin
- /system/file/upload
- /system/file/uploads
- /system/file/uploadImage
- /ec/device-api/report
- /ec/device-api/heartbeat
# 名称 # 名称
name: RuoYi name: RuoYi
# 版本 # 版本
@@ -12,6 +17,8 @@ ruoyi:
copyrightYear: 2021 copyrightYear: 2021
# 实例演示开关 # 实例演示开关
demoEnabled: true 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) # 文件路径 示例( Windows配置D:/ruoyi/uploadPath,Linux配置 /home/ruoyi/uploadPath)
profile: D:/ruoyi/uploadPath profile: D:/ruoyi/uploadPath
# 获取ip地址开关 # 获取ip地址开关
@@ -134,7 +141,6 @@ mybatis-plus:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapper/**/*Mapper.xml mapper-locations: classpath*:mapper/**/*Mapper.xml
global-config: global-config:
identifier-generator: com.ruoyi.framework.config.CustomKeyGenerator
db-config: db-config:
id-type: auto id-type: auto
logic-not-delete-value: 1 logic-not-delete-value: 1
@@ -10,107 +10,113 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
@ConfigurationProperties(prefix = "ruoyi") @ConfigurationProperties(prefix = "ruoyi")
public class RuoYiConfig public class RuoYiConfig {
{ /**
/** 项目名称 */ * 项目名称
*/
private String name; private String name;
/** 版本 */ /**
* 版本
*/
private String version; private String version;
/** 版权年份 */ /**
* 版权年份
*/
private String copyrightYear; private String copyrightYear;
/** 实例演示开关 */ /**
* 实例演示开关
*/
private boolean demoEnabled; private boolean demoEnabled;
/** 上传路径 */ private String reqUrl;
/**
* 上传路径
*/
private static String profile; private static String profile;
/** 获取地址开关 */ /**
* 获取地址开关
*/
private static boolean addressEnabled; private static boolean addressEnabled;
public String getName() public String getName() {
{
return name; return name;
} }
public void setName(String name) public void setReqUrl(String url) {
{ reqUrl = url;
}
public void setName(String name) {
this.name = name; this.name = name;
} }
public String getVersion() public String getReqUrl() {
{ return reqUrl;
}
public String getVersion() {
return version; return version;
} }
public void setVersion(String version) public void setVersion(String version) {
{
this.version = version; this.version = version;
} }
public String getCopyrightYear() public String getCopyrightYear() {
{
return copyrightYear; return copyrightYear;
} }
public void setCopyrightYear(String copyrightYear) public void setCopyrightYear(String copyrightYear) {
{
this.copyrightYear = copyrightYear; this.copyrightYear = copyrightYear;
} }
public boolean isDemoEnabled() public boolean isDemoEnabled() {
{
return demoEnabled; return demoEnabled;
} }
public void setDemoEnabled(boolean demoEnabled) public void setDemoEnabled(boolean demoEnabled) {
{
this.demoEnabled = demoEnabled; this.demoEnabled = demoEnabled;
} }
public static String getProfile() public static String getProfile() {
{
return profile; return profile;
} }
public void setProfile(String profile) public void setProfile(String profile) {
{
RuoYiConfig.profile = profile; RuoYiConfig.profile = profile;
} }
public static boolean isAddressEnabled() public static boolean isAddressEnabled() {
{
return addressEnabled; return addressEnabled;
} }
public void setAddressEnabled(boolean addressEnabled) public void setAddressEnabled(boolean addressEnabled) {
{
RuoYiConfig.addressEnabled = addressEnabled; RuoYiConfig.addressEnabled = addressEnabled;
} }
/** /**
* 获取头像上传路径 * 获取头像上传路径
*/ */
public static String getAvatarPath() public static String getAvatarPath() {
{
return getProfile() + "/avatar"; return getProfile() + "/avatar";
} }
/** /**
* 获取下载路径 * 获取下载路径
*/ */
public static String getDownloadPath() public static String getDownloadPath() {
{
return getProfile() + "/download/"; return getProfile() + "/download/";
} }
/** /**
* 获取上传路径 * 获取上传路径
*/ */
public static String getUploadPath() public static String getUploadPath() {
{
return getProfile() + "/upload"; return getProfile() + "/upload";
} }
} }
@@ -128,7 +128,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers("/life/housingEstate/all-by-letter").permitAll() .antMatchers("/life/housingEstate/all-by-letter").permitAll()
.antMatchers("/system/config/getVerifyStatus").permitAll() .antMatchers("/system/config/getVerifyStatus").permitAll()
.antMatchers("/system/config/setVerifyStatus").permitAll() .antMatchers("/system/config/setVerifyStatus").permitAll()
.antMatchers("/ec/device-api/**").anonymous()
.anyRequest().authenticated() .anyRequest().authenticated()
.and() .and()
.headers().frameOptions().disable(); .headers().frameOptions().disable();
@@ -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<MultipartFile> files,
@RequestParam(value = "module", required = false, defaultValue = "common") String module) {
try {
List<String> 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());
}
}
}
@@ -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<String> uploadFiles(List<MultipartFile> files, String module);
boolean deleteFile(String filePath);
String getFileUrl(String filePath);
}
@@ -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<String> uploadFiles(List<MultipartFile> files, String module) {
List<String> 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;
}
}