代码提交

This commit is contained in:
liang.chao 2025-09-17 14:55:27 +08:00
parent eeb590d056
commit a290981d46
9 changed files with 233 additions and 133 deletions

View File

@ -6,7 +6,12 @@ import com.bonus.common.core.controller.BaseController;
import com.bonus.common.core.domain.R; import com.bonus.common.core.domain.R;
import com.bonus.common.core.page.TableDataInfo; import com.bonus.common.core.page.TableDataInfo;
import com.bonus.common.enums.OperaType; import com.bonus.common.enums.OperaType;
import com.bonus.common.utils.SecurityUtils;
import com.bonus.common.utils.bean.FileDto;
import com.bonus.common.utils.file.FileUploadUtils;
import com.bonus.common.utils.file.FileUtils;
import com.bonus.web.domain.DaKyProFilesContentsDto; import com.bonus.web.domain.DaKyProFilesContentsDto;
import com.bonus.web.domain.FilesClassifyNameStandardDto;
import com.bonus.web.domain.ProjectDto; import com.bonus.web.domain.ProjectDto;
import com.bonus.web.domain.vo.DaKyProFilesContentsVo; import com.bonus.web.domain.vo.DaKyProFilesContentsVo;
import com.bonus.web.mapper.FileManageMapper; import com.bonus.web.mapper.FileManageMapper;
@ -17,10 +22,13 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import static com.bonus.common.utils.SecurityUtils.getLoginUser;
/** /**
* @Authorliang.chao * @Authorliang.chao
* @Date2025/9/11 - 13:29 * @Date2025/9/11 - 13:29
@ -107,7 +115,7 @@ public class FileManagementController extends BaseController {
@PostMapping("addFileManageRight") @PostMapping("addFileManageRight")
@SysLog(title = "新增右侧档案树", module = "档案管理->档案目录管理", businessType = OperaType.INSERT, details = "新增右侧档案树", logType = 1) @SysLog(title = "新增右侧档案树", module = "档案管理->档案目录管理", businessType = OperaType.INSERT, details = "新增右侧档案树", logType = 1)
@RequiresPermissions("file:manage:add") @RequiresPermissions("file:manage:add")
public R saveArchivalCatalogue(@ModelAttribute @Validated DaKyProFilesContentsVo dto) { public R saveArchivalCatalogue(@ModelAttribute @Validated DaKyProFilesContentsVo dto, @RequestParam("file") MultipartFile file) {
try { try {
if (dto.getParentId() == null) { if (dto.getParentId() == null) {
return R.fail("父级有误"); return R.fail("父级有误");
@ -115,6 +123,35 @@ public class FileManagementController extends BaseController {
if (dto.getLevel() == null) { if (dto.getLevel() == null) {
return R.fail("级别有误"); return R.fail("级别有误");
} }
// 查询档案名称是否重复
Integer i = fileManageMapper.selectFileManage(dto);
if (i > 0) {
return R.fail("档案名称重复");
}
if (file != null && !file.isEmpty()) {
// 判断是否包含文件命名规范
List<FilesClassifyNameStandardDto> list = fileManageMapper.getFilesClassifyNameStandard();
for (FilesClassifyNameStandardDto s : list) {
if (s.getStandardType().equals("1") && !file.getOriginalFilename().contains(s.getStandardName())) {
return R.fail("文件命名需包含" + s.getStandardName());
} else if (s.getStandardType().equals("0") && file.getOriginalFilename().contains(s.getStandardName())) {
return R.fail("文件命名不能包含" + s.getStandardName());
}
}
FileDto upload = FileUtils.upload(file);
dto.setFilePath(upload.getFilePath());
dto.setFileSize(upload.getFileSize());
dto.setFileName(upload.getFileName());
dto.setFileType(upload.getFileType());
dto.setSuffixName(upload.getSuffixName());
dto.setUpdateUserId(getLoginUser().getUserId());
dto.setUpdateUserName(getLoginUser().getUsername());
dto.setCreateUserId(getLoginUser().getUserId());
dto.setCreateUserName(getLoginUser().getUsername());
fileManageMapper.saveFileSource(dto);
} else if (file == null || file.isEmpty()) {
return R.fail("请上传文件");
}
return fileManageService.saveFileManage(dto); return fileManageService.saveFileManage(dto);
} catch (Exception e) { } catch (Exception e) {
log.error(e.toString(), e); log.error(e.toString(), e);
@ -152,8 +189,32 @@ public class FileManagementController extends BaseController {
@PostMapping("updateFileManageRight") @PostMapping("updateFileManageRight")
@SysLog(title = "修改档案", module = "档案管理->档案目录管理", businessType = OperaType.UPDATE, details = "修改档案", logType = 1) @SysLog(title = "修改档案", module = "档案管理->档案目录管理", businessType = OperaType.UPDATE, details = "修改档案", logType = 1)
@RequiresPermissions("file:manage:update") @RequiresPermissions("file:manage:update")
public R updateFileManage(@ModelAttribute @Validated DaKyProFilesContentsVo dto) { public R updateFileManage(@ModelAttribute @Validated DaKyProFilesContentsVo dto, @RequestParam("file") MultipartFile file) {
try { try {
dto.setUpdateUserId(getLoginUser().getUserId());
dto.setUpdateUserName(getLoginUser().getUsername());
Integer i = fileManageMapper.selectFileManage(dto);
if (i > 0) {
return R.fail("档案名称重复");
}
if (file != null && !file.isEmpty()) {
// 判断是否包含文件命名规范
List<FilesClassifyNameStandardDto> list = fileManageMapper.getFilesClassifyNameStandard();
for (FilesClassifyNameStandardDto s : list) {
if (s.getStandardType().equals("1") && !file.getOriginalFilename().contains(s.getStandardName())) {
return R.fail("文件命名需包含" + s.getStandardName());
} else if (s.getStandardType().equals("0") && file.getOriginalFilename().contains(s.getStandardName())) {
return R.fail("文件命名不能包含" + s.getStandardName());
}
}
FileDto upload = FileUtils.upload(file);
dto.setFilePath(upload.getFilePath());
dto.setFileSize(upload.getFileSize());
dto.setFileName(upload.getFileName());
dto.setFileType(upload.getFileType());
dto.setSuffixName(upload.getSuffixName());
fileManageMapper.updateFileSource(dto);
}
return fileManageService.updateFileManage(dto); return fileManageService.updateFileManage(dto);
} catch (Exception e) { } catch (Exception e) {
log.error(e.toString(), e); log.error(e.toString(), e);

View File

@ -125,6 +125,10 @@ public class DaKyProFilesContentsDto {
* 文件名称 * 文件名称
*/ */
private String fileName; private String fileName;
/**
* 文件大小
*/
private String fileSize;
/** /**
* 文件类型 * 文件类型
*/ */

View File

@ -127,6 +127,15 @@ public class DaKyProFilesContentsVo {
* 文件类型 * 文件类型
*/ */
private String fileType; private String fileType;
/**
* 文件大小
*/
private String fileSize;
/**
* 文件后缀名
*/
private String suffixName;
/** /**
* 资源类型 * 资源类型
*/ */

View File

@ -1,6 +1,7 @@
package com.bonus.web.mapper; package com.bonus.web.mapper;
import com.bonus.web.domain.DaKyProFilesContentsDto; import com.bonus.web.domain.DaKyProFilesContentsDto;
import com.bonus.web.domain.FilesClassifyNameStandardDto;
import com.bonus.web.domain.vo.DaKyProFilesContentsVo; import com.bonus.web.domain.vo.DaKyProFilesContentsVo;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
@ -24,7 +25,6 @@ public interface FileManageMapper {
Integer updateFileManage(DaKyProFilesContentsDto dto); Integer updateFileManage(DaKyProFilesContentsDto dto);
Integer updateFileManage(DaKyProFilesContentsVo dto); Integer updateFileManage(DaKyProFilesContentsVo dto);
Integer updateFileSource(DaKyProFilesContentsDto dto);
Integer updateFileSource(DaKyProFilesContentsVo dto); Integer updateFileSource(DaKyProFilesContentsVo dto);
Integer delFileSource(DaKyProFilesContentsDto dto); Integer delFileSource(DaKyProFilesContentsDto dto);
@ -34,7 +34,7 @@ public interface FileManageMapper {
Integer selectFileManage(DaKyProFilesContentsDto dto); Integer selectFileManage(DaKyProFilesContentsDto dto);
Integer selectFileManage(DaKyProFilesContentsVo dto); Integer selectFileManage(DaKyProFilesContentsVo dto);
List<String> getFilesClassifyNameStandard(); List<FilesClassifyNameStandardDto> getFilesClassifyNameStandard();
Integer updateIntegrityStatus(DaKyProFilesContentsDto dto); Integer updateIntegrityStatus(DaKyProFilesContentsDto dto);

View File

@ -64,25 +64,6 @@ public class FileManageServiceImpl implements FileManageService {
@Override @Override
public R saveFileManage(DaKyProFilesContentsVo dto) { public R saveFileManage(DaKyProFilesContentsVo dto) {
// 查询档案名称是否重复
Integer i = fileManageMapper.selectFileManage(dto);
if (i > 0) {
return R.fail("档案名称重复");
}
dto.setCreateUserId(getLoginUser().getUserId());
dto.setCreateUserName(getLoginUser().getUsername());
dto.setUpdateUserId(SecurityUtils.getLoginUser().getUserId());
dto.setUpdateUserName(SecurityUtils.getLoginUser().getUsername());
if (StringUtils.isNotBlank(dto.getFilePath())) {
// 判断是否包含文件命名规范
List<String> list = fileManageMapper.getFilesClassifyNameStandard();
for (String s : list) {
if (!dto.getFilePath().contains(s)) {
return R.fail("文件命名不符合规范");
}
}
fileManageMapper.saveFileSource(dto);
}
String uuid32 = UUID.randomUUID().toString().replace("-", "").toLowerCase(); String uuid32 = UUID.randomUUID().toString().replace("-", "").toLowerCase();
dto.setId(uuid32); dto.setId(uuid32);
return R.ok(fileManageMapper.saveFileManage(dto)); return R.ok(fileManageMapper.saveFileManage(dto));
@ -101,16 +82,6 @@ public class FileManageServiceImpl implements FileManageService {
@Override @Override
public R updateFileManage(DaKyProFilesContentsVo dto) { public R updateFileManage(DaKyProFilesContentsVo dto) {
dto.setUpdateUserId(getLoginUser().getUserId());
dto.setUpdateUserName(getLoginUser().getUsername());
Integer i = fileManageMapper.selectFileManage(dto);
if (i > 0) {
return R.fail("档案名称重复");
}
fileManageMapper.updateFileSource(dto);
if (StringUtils.isBlank(dto.getFilePath())) {
dto.setId(null);
}
return R.ok(fileManageMapper.updateFileManage(dto)); return R.ok(fileManageMapper.updateFileManage(dto));
} }

View File

@ -99,6 +99,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
source_file_name = #{sourceFileName}, source_file_name = #{sourceFileName},
file_name = #{fileName}, file_name = #{fileName},
file_type = #{fileType}, file_type = #{fileType},
file_size = #{fileSize},
source_type = #{sourceType}, source_type = #{sourceType},
update_user_id = #{updateUserId}, update_user_id = #{updateUserId},
update_user_name = #{updateUserName}, update_user_name = #{updateUserName},
@ -177,14 +178,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
and id != #{id} and id != #{id}
</if> </if>
</select> </select>
<select id="getFilesClassifyNameStandard" resultType="java.lang.String">
SELECT
dkfcns.standard_name
FROM
da_ky_files_classify_name_standard dkfcns
WHERE
dkfcns.del_flag = '1' and standard_type = '1'
</select>
<select id="getMaxSort" resultType="java.lang.Integer"> <select id="getMaxSort" resultType="java.lang.Integer">
SELECT SELECT
max(dkpfc.sort) max(dkpfc.sort)
@ -210,4 +204,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
WHERE WHERE
dkpfc.id = #{id} dkpfc.id = #{id}
</select> </select>
<select id="getFilesClassifyNameStandard" resultType="com.bonus.web.domain.FilesClassifyNameStandardDto">
SELECT
dkfcns.standard_name AS standardName,
dkfcns.standard_type AS standardType
FROM
da_ky_files_classify_name_standard dkfcns
WHERE
dkfcns.del_flag = '1'
</select>
</mapper> </mapper>

View File

@ -51,7 +51,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<select id="getClassifyNameStandardList" resultType="com.bonus.web.domain.FilesClassifyNameStandardDto"> <select id="getClassifyNameStandardList" resultType="com.bonus.web.domain.FilesClassifyNameStandardDto">
SELECT SELECT
dkfcns.id, dkfcns.id,
dkfcns.standard_type AS standardType, dksdd.dict_label AS standardType,
dkfcns.standard_name AS standardName, dkfcns.standard_name AS standardName,
dkfcns.remark, dkfcns.remark,
dkfcns.create_time AS createTime, dkfcns.create_time AS createTime,

View File

@ -0,0 +1,21 @@
package com.bonus.common.utils.bean;
import lombok.Data;
/**
* @Authorliang.chao
* @Date2025/9/17 - 13:56
*/
@Data
public class FileDto {
// 文件名称
private String fileName;
// 文件路径
private String filePath;
// 文件大小
private String fileSize;
// 文件类型 1.图片 2.文件
private String fileType;
// 文件后缀名
private String suffixName;
}

View File

@ -9,8 +9,15 @@ import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.bonus.common.core.domain.R;
import com.bonus.common.utils.bean.FileDto;
import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
@ -19,47 +26,61 @@ import com.bonus.common.constant.Constants;
import com.bonus.common.utils.DateUtils; import com.bonus.common.utils.DateUtils;
import com.bonus.common.utils.StringUtils; import com.bonus.common.utils.StringUtils;
import com.bonus.common.utils.uuid.IdUtils; import com.bonus.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
/** /**
* 文件处理工具类 * 文件处理工具类
* *
* @author bonus * @author bonus
*/ */
public class FileUtils public class FileUtils {
{
public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+"; public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
// 常见的图片扩展名小写
// 常见的图片扩展名小写
private static final Set<String> IMAGE_EXTENSIONS;
static {
HashSet<String> set = new HashSet<>();
set.add("jpg");
set.add("jpeg");
set.add("png");
set.add("gif");
set.add("bmp");
set.add("webp");
set.add("tiff");
set.add("svg");
set.add("ico");
IMAGE_EXTENSIONS = Collections.unmodifiableSet(set);
}
@Value("${bonus.profile}")
private static String uploadDir;
/** /**
* 输出指定文件的byte数组 * 输出指定文件的byte数组
* *
* @param filePath 文件路径 * @param filePath 文件路径
* @param os 输出流 * @param os 输出流
* @return * @return
*/ */
public static void writeBytes(String filePath, OutputStream os) throws IOException public static void writeBytes(String filePath, OutputStream os) throws IOException {
{
FileInputStream fis = null; FileInputStream fis = null;
try try {
{
File file = new File(filePath); File file = new File(filePath);
if (!file.exists()) if (!file.exists()) {
{
throw new FileNotFoundException(filePath); throw new FileNotFoundException(filePath);
} }
fis = new FileInputStream(file); fis = new FileInputStream(file);
byte[] b = new byte[1024]; byte[] b = new byte[1024];
int length; int length;
while ((length = fis.read(b)) > 0) while ((length = fis.read(b)) > 0) {
{
os.write(b, 0, length); os.write(b, 0, length);
} }
} } catch (IOException e) {
catch (IOException e)
{
throw e; throw e;
} } finally {
finally
{
IOUtils.close(os); IOUtils.close(os);
IOUtils.close(fis); IOUtils.close(fis);
} }
@ -72,33 +93,28 @@ public class FileUtils
* @return 目标文件 * @return 目标文件
* @throws IOException IO异常 * @throws IOException IO异常
*/ */
public static String writeImportBytes(byte[] data) throws IOException public static String writeImportBytes(byte[] data) throws IOException {
{
return writeBytes(data, BonusConfig.getImportPath()); return writeBytes(data, BonusConfig.getImportPath());
} }
/** /**
* 写数据到文件中 * 写数据到文件中
* *
* @param data 数据 * @param data 数据
* @param uploadDir 目标文件 * @param uploadDir 目标文件
* @return 目标文件 * @return 目标文件
* @throws IOException IO异常 * @throws IOException IO异常
*/ */
public static String writeBytes(byte[] data, String uploadDir) throws IOException public static String writeBytes(byte[] data, String uploadDir) throws IOException {
{
FileOutputStream fos = null; FileOutputStream fos = null;
String pathName = ""; String pathName = "";
try try {
{
String extension = getFileExtendName(data); String extension = getFileExtendName(data);
pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension; pathName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName); File file = FileUploadUtils.getAbsoluteFile(uploadDir, pathName);
fos = new FileOutputStream(file); fos = new FileOutputStream(file);
fos.write(data); fos.write(data);
} } finally {
finally
{
IOUtils.close(fos); IOUtils.close(fos);
} }
return FileUploadUtils.getPathFileName(uploadDir, pathName); return FileUploadUtils.getPathFileName(uploadDir, pathName);
@ -106,28 +122,25 @@ public class FileUtils
/** /**
* 移除路径中的请求前缀片段 * 移除路径中的请求前缀片段
* *
* @param filePath 文件路径 * @param filePath 文件路径
* @return 移除后的文件路径 * @return 移除后的文件路径
*/ */
public static String stripPrefix(String filePath) public static String stripPrefix(String filePath) {
{
return StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX); return StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX);
} }
/** /**
* 删除文件 * 删除文件
* *
* @param filePath 文件 * @param filePath 文件
* @return * @return
*/ */
public static boolean deleteFile(String filePath) public static boolean deleteFile(String filePath) {
{
boolean flag = false; boolean flag = false;
File file = new File(filePath); File file = new File(filePath);
// 路径为文件且不为空则进行删除 // 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) if (file.isFile() && file.exists()) {
{
flag = file.delete(); flag = file.delete();
} }
return flag; return flag;
@ -135,32 +148,28 @@ public class FileUtils
/** /**
* 文件名称验证 * 文件名称验证
* *
* @param filename 文件名称 * @param filename 文件名称
* @return true 正常 false 非法 * @return true 正常 false 非法
*/ */
public static boolean isValidFilename(String filename) public static boolean isValidFilename(String filename) {
{
return filename.matches(FILENAME_PATTERN); return filename.matches(FILENAME_PATTERN);
} }
/** /**
* 检查文件是否可下载 * 检查文件是否可下载
* *
* @param resource 需要下载的文件 * @param resource 需要下载的文件
* @return true 正常 false 非法 * @return true 正常 false 非法
*/ */
public static boolean checkAllowDownload(String resource) public static boolean checkAllowDownload(String resource) {
{
// 禁止目录上跳级别 // 禁止目录上跳级别
if (StringUtils.contains(resource, "..")) if (StringUtils.contains(resource, "..")) {
{
return false; return false;
} }
// 检查允许下载的文件规则 // 检查允许下载的文件规则
if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) if (ArrayUtils.contains(MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, FileTypeUtils.getFileType(resource))) {
{
return true; return true;
} }
@ -170,33 +179,25 @@ public class FileUtils
/** /**
* 下载文件名重新编码 * 下载文件名重新编码
* *
* @param request 请求对象 * @param request 请求对象
* @param fileName 文件名 * @param fileName 文件名
* @return 编码后的文件名 * @return 编码后的文件名
*/ */
public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException public static String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
{
final String agent = request.getHeader("USER-AGENT"); final String agent = request.getHeader("USER-AGENT");
String filename = fileName; String filename = fileName;
if (agent.contains("MSIE")) if (agent.contains("MSIE")) {
{
// IE浏览器 // IE浏览器
filename = URLEncoder.encode(filename, "utf-8"); filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+", " "); filename = filename.replace("+", " ");
} } else if (agent.contains("Firefox")) {
else if (agent.contains("Firefox"))
{
// 火狐浏览器 // 火狐浏览器
filename = new String(fileName.getBytes(), "ISO8859-1"); filename = new String(fileName.getBytes(), "ISO8859-1");
} } else if (agent.contains("Chrome")) {
else if (agent.contains("Chrome"))
{
// google浏览器 // google浏览器
filename = URLEncoder.encode(filename, "utf-8"); filename = URLEncoder.encode(filename, "utf-8");
} } else {
else
{
// 其它浏览器 // 其它浏览器
filename = URLEncoder.encode(filename, "utf-8"); filename = URLEncoder.encode(filename, "utf-8");
} }
@ -206,11 +207,10 @@ public class FileUtils
/** /**
* 下载文件名重新编码 * 下载文件名重新编码
* *
* @param response 响应对象 * @param response 响应对象
* @param realFileName 真实文件名 * @param realFileName 真实文件名
*/ */
public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
{
String percentEncodedFileName = percentEncode(realFileName); String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder(); StringBuilder contentDispositionValue = new StringBuilder();
@ -232,36 +232,27 @@ public class FileUtils
* @param s 需要百分号编码的字符串 * @param s 需要百分号编码的字符串
* @return 百分号编码后的字符串 * @return 百分号编码后的字符串
*/ */
public static String percentEncode(String s) throws UnsupportedEncodingException public static String percentEncode(String s) throws UnsupportedEncodingException {
{
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString()); String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20"); return encode.replaceAll("\\+", "%20");
} }
/** /**
* 获取图像后缀 * 获取图像后缀
* *
* @param photoByte 图像数据 * @param photoByte 图像数据
* @return 后缀名 * @return 后缀名
*/ */
public static String getFileExtendName(byte[] photoByte) public static String getFileExtendName(byte[] photoByte) {
{
String strFileExtendName = "jpg"; String strFileExtendName = "jpg";
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56) if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) && ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97)) {
{
strFileExtendName = "gif"; strFileExtendName = "gif";
} } else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70)) {
else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
{
strFileExtendName = "jpg"; strFileExtendName = "jpg";
} } else if ((photoByte[0] == 66) && (photoByte[1] == 77)) {
else if ((photoByte[0] == 66) && (photoByte[1] == 77))
{
strFileExtendName = "bmp"; strFileExtendName = "bmp";
} } else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71)) {
else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
{
strFileExtendName = "png"; strFileExtendName = "png";
} }
return strFileExtendName; return strFileExtendName;
@ -269,14 +260,12 @@ public class FileUtils
/** /**
* 获取文件名称 /profile/upload/2022/04/16/bonus.png -- bonus.png * 获取文件名称 /profile/upload/2022/04/16/bonus.png -- bonus.png
* *
* @param fileName 路径名称 * @param fileName 路径名称
* @return 没有文件路径的名称 * @return 没有文件路径的名称
*/ */
public static String getName(String fileName) public static String getName(String fileName) {
{ if (fileName == null) {
if (fileName == null)
{
return null; return null;
} }
int lastUnixPos = fileName.lastIndexOf('/'); int lastUnixPos = fileName.lastIndexOf('/');
@ -287,17 +276,59 @@ public class FileUtils
/** /**
* 获取不带后缀文件名称 /profile/upload/2022/04/16/bonus.png -- bonus * 获取不带后缀文件名称 /profile/upload/2022/04/16/bonus.png -- bonus
* *
* @param fileName 路径名称 * @param fileName 路径名称
* @return 没有文件路径和后缀的名称 * @return 没有文件路径和后缀的名称
*/ */
public static String getNameNotSuffix(String fileName) public static String getNameNotSuffix(String fileName) {
{ if (fileName == null) {
if (fileName == null)
{
return null; return null;
} }
String baseName = FilenameUtils.getBaseName(fileName); String baseName = FilenameUtils.getBaseName(fileName);
return baseName; return baseName;
} }
public static final FileDto upload(MultipartFile file) throws IOException {
FileDto bean = new FileDto();
if (file != null && !file.isEmpty()) {
// 验证文件类型
String originalFileName = file.getOriginalFilename();
String fileExtension = originalFileName != null ? originalFileName.split("\\.")[1] : "";
if (isImage(fileExtension)) {
bean.setFileType("1");
} else {
bean.setFileType("2");
}
File targetDir = new File(uploadDir);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
File targetFile = new File(uploadDir, fileName);
file.transferTo(targetFile);
String pathName = targetFile.getAbsolutePath();
bean.setFilePath(pathName);
bean.setFileName(fileName);
bean.setFileSize(file.getSize() + "");
bean.setSuffixName(fileExtension);
return bean;
} else {
return bean;
}
}
/**
* 根据文件扩展名判断是否为图片
*
* @param fileExtension 文件扩展名例如 "jpg", "png", "pdf"
* @return true 表示是图片false 表示是普通文件
*/
public static boolean isImage(String fileExtension) {
if (fileExtension == null || fileExtension.trim().isEmpty()) {
return false;
}
String ext = fileExtension.toLowerCase().trim();
return IMAGE_EXTENSIONS.contains(ext);
}
} }