Commit 5360d775 authored by lcl's avatar lcl

资料文档相关代码迁移

parent a9189dd4
package com.dsk.common.exception.file;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import java.util.Arrays;
/**
* 文件上传 误异常类
*
* @author dsk
*/
public class InvalidExtensionException extends FileUploadException
{
private static final long serialVersionUID = 1L;
private String[] allowedExtension;
private String extension;
private String filename;
public InvalidExtensionException(String[] allowedExtension, String extension, String filename)
{
super("文件[" + filename + "]后缀[" + extension + "]不正确,请上传" + Arrays.toString(allowedExtension) + "格式");
this.allowedExtension = allowedExtension;
this.extension = extension;
this.filename = filename;
}
public String[] getAllowedExtension()
{
return allowedExtension;
}
public String getExtension()
{
return extension;
}
public String getFilename()
{
return filename;
}
public static class InvalidImageExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidImageExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidFlashExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidFlashExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidMediaExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidMediaExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
public static class InvalidVideoExtensionException extends InvalidExtensionException
{
private static final long serialVersionUID = 1L;
public InvalidVideoExtensionException(String[] allowedExtension, String extension, String filename)
{
super(allowedExtension, extension, filename);
}
}
}
package com.dsk.common.utils.file;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
/**
* 文件类型工具类
*
* @author dsk
*/
public class FileTypeUtils
{
/**
* 获取文件类型
* <p>
* 例如: dsk.txt, 返回: txt
*
* @param file 文件名
* @return 后缀(不含".")
*/
public static String getFileType(File file)
{
if (null == file)
{
return StringUtils.EMPTY;
}
return getFileType(file.getName());
}
/**
* 获取文件类型
* <p>
* 例如: dsk.txt, 返回: txt
*
* @param fileName 文件名
* @return 后缀(不含".")
*/
public static String getFileType(String fileName)
{
int separatorIndex = fileName.lastIndexOf(".");
if (separatorIndex < 0)
{
return "";
}
return fileName.substring(separatorIndex + 1).toLowerCase();
}
/**
* 获取文件类型
*
* @param photoByte 文件字节码
* @return 后缀(不含".")
*/
public static String getFileExtendName(byte[] photoByte)
{
String strFileExtendName = "JPG";
if ((photoByte[0] == 71) && (photoByte[1] == 73) && (photoByte[2] == 70) && (photoByte[3] == 56)
&& ((photoByte[4] == 55) || (photoByte[4] == 57)) && (photoByte[5] == 97))
{
strFileExtendName = "GIF";
}
else if ((photoByte[6] == 74) && (photoByte[7] == 70) && (photoByte[8] == 73) && (photoByte[9] == 70))
{
strFileExtendName = "JPG";
}
else if ((photoByte[0] == 66) && (photoByte[1] == 77))
{
strFileExtendName = "BMP";
}
else if ((photoByte[1] == 80) && (photoByte[2] == 78) && (photoByte[3] == 71))
{
strFileExtendName = "PNG";
}
return strFileExtendName;
}
}
package com.dsk.common.utils.file;
import com.dsk.common.exception.file.FileNameLengthLimitExceededException;
import com.dsk.common.exception.file.FileSizeLimitExceededException;
import com.dsk.common.exception.file.InvalidExtensionException;
import com.dsk.common.utils.DateUtils;
import com.dsk.common.utils.StringUtils;
import com.dsk.common.utils.uuid.Seq;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Objects;
/**
* 文件上传工具类
*
* @author dsk
*/
public class FileUploadUtils
{
/**
* 默认大小 50M
*/
public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;
/**
* 默认的文件名最大长度 100
*/
public static final int DEFAULT_FILE_NAME_LENGTH = 100;
/**
* 默认上传的地址
*/
private static String defaultBaseDir = "/home/server/dsk-operate-sys/uploadPath/";
/**
* 资源映射路径 前缀
*/
public static final String RESOURCE_PREFIX = "/profile";
public static void setDefaultBaseDir(String defaultBaseDir)
{
FileUploadUtils.defaultBaseDir = defaultBaseDir;
}
public static String getDefaultBaseDir()
{
return defaultBaseDir;
}
/**
* 以默认配置进行文件上传
*
* @param file 上传的文件
* @return 文件名称
* @throws Exception
*/
public static final String upload(MultipartFile file) throws IOException
{
try
{
return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
}
catch (Exception e)
{
throw new IOException(e.getMessage(), e);
}
}
/**
* 根据文件路径上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @return 文件名称
* @throws IOException
*/
public static final String upload(String baseDir, MultipartFile file) throws IOException
{
try
{
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
}
catch (Exception e)
{
throw new IOException(e.getMessage(), e);
}
}
/**
* 文件上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @param allowedExtension 上传文件类型
* @return 返回上传成功的文件名
* @throws FileSizeLimitExceededException 如果超出最大大小
* @throws FileNameLengthLimitExceededException 文件名太长
* @throws IOException 比如读写文件出错时
*/
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException
{
int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
{
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
}
assertAllowed(file, allowedExtension);
// String fileName = extractFilename(file);
// String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();
String absPath = getAbsoluteFile(baseDir, file.getOriginalFilename()).getAbsolutePath();
file.transferTo(Paths.get(absPath));
// return getPathFileName(baseDir, fileName);
return baseDir+file.getOriginalFilename();
}
/**
* 编码文件名
*/
public static final String extractFilename(MultipartFile file)
{
return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));
}
public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
{
File desc = new File(uploadDir + File.separator + fileName);
if (!desc.exists())
{
if (!desc.getParentFile().exists())
{
desc.getParentFile().mkdirs();
}
}
return desc;
}
public static final String getPathFileName(String uploadDir, String fileName) throws IOException
{
int dirLastIndex = getDefaultBaseDir().length() + 1;
String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
return RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
}
/**
* 文件大小校验
*
* @param file 上传的文件
* @return
* @throws FileSizeLimitExceededException 如果超出最大大小
*/
public static final 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))
{
if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION)
{
throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
fileName);
}
else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION)
{
throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
fileName);
}
else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION)
{
throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
fileName);
}
else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION)
{
throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,
fileName);
}
else
{
throw new InvalidExtensionException(allowedExtension, extension, fileName);
}
}
}
/**
* 判断MIME类型是否是允许的MIME类型
*
* @param extension
* @param allowedExtension
* @return
*/
public static final boolean isAllowedExtension(String extension, String[] allowedExtension)
{
for (String str : allowedExtension)
{
if (str.equalsIgnoreCase(extension))
{
return true;
}
}
return false;
}
/**
* 获取文件名的后缀
*
* @param file 表单文件
* @return 后缀名
*/
public static final String getExtension(MultipartFile file)
{
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
if (StringUtils.isEmpty(extension))
{
extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
}
return extension;
}
}
......@@ -37,4 +37,22 @@ public class MimeTypeUtils {
// pdf
"pdf"};
public static String getExtension(String prefix)
{
switch (prefix)
{
case IMAGE_PNG:
return "png";
case IMAGE_JPG:
return "jpg";
case IMAGE_JPEG:
return "jpeg";
case IMAGE_BMP:
return "bmp";
case IMAGE_GIF:
return "gif";
default:
return "";
}
}
}
package com.dsk.common.utils.uuid;
/**
* ID生成器工具类
*
* @author dsk
*/
public class IdUtils
{
/**
* 获取随机UUID
*
* @return 随机UUID
*/
public static String randomUUID()
{
return UUID.randomUUID().toString();
}
/**
* 简化的UUID,去掉了横线
*
* @return 简化的UUID,去掉了横线
*/
public static String simpleUUID()
{
return UUID.randomUUID().toString(true);
}
/**
* 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 随机UUID
*/
public static String fastUUID()
{
return UUID.fastUUID().toString();
}
/**
* 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID
*
* @return 简化的UUID,去掉了横线
*/
public static String fastSimpleUUID()
{
return UUID.fastUUID().toString(true);
}
}
package com.dsk.common.utils.uuid;
import com.dsk.common.utils.DateUtils;
import com.dsk.common.utils.StringUtils;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author dsk 序列生成类
*/
public class Seq
{
// 通用序列类型
public static final String commSeqType = "COMMON";
// 上传序列类型
public static final String uploadSeqType = "UPLOAD";
// 通用接口序列数
private static AtomicInteger commSeq = new AtomicInteger(1);
// 上传接口序列数
private static AtomicInteger uploadSeq = new AtomicInteger(1);
// 机器标识
private static final String machineCode = "A";
/**
* 获取通用序列号
*
* @return 序列值
*/
public static String getId()
{
return getId(commSeqType);
}
/**
* 默认16位序列号 yyMMddHHmmss + 一位机器标识 + 3长度循环递增字符串
*
* @return 序列值
*/
public static String getId(String type)
{
AtomicInteger atomicInt = commSeq;
if (uploadSeqType.equals(type))
{
atomicInt = uploadSeq;
}
return getId(atomicInt, 3);
}
/**
* 通用接口序列号 yyMMddHHmmss + 一位机器标识 + length长度循环递增字符串
*
* @param atomicInt 序列数
* @param length 数值长度
* @return 序列值
*/
public static String getId(AtomicInteger atomicInt, int length)
{
String result = DateUtils.dateTimeNow();
result += machineCode;
result += getSeq(atomicInt, length);
return result;
}
/**
* 序列循环递增字符串[1, 10 的 (length)幂次方), 用0左补齐length位数
*
* @return 序列值
*/
private synchronized static String getSeq(AtomicInteger atomicInt, int length)
{
// 先取值再+1
int value = atomicInt.getAndIncrement();
// 如果更新后值>=10 的 (length)幂次方则重置为1
int maxSeq = (int) Math.pow(10, length);
if (atomicInt.get() >= maxSeq)
{
atomicInt.set(1);
}
// 转字符串,用0左补齐
return StringUtils.padl(value, length);
}
}
This diff is collapsed.
......@@ -2,13 +2,13 @@ package com.dsk.biz.controller;
import com.dsk.biz.domain.bo.BusinessIdDto;
import com.dsk.biz.domain.vo.BusinessFileVo;
import com.dsk.biz.utils.OldFileUtils;
import com.dsk.common.core.controller.BaseController;
import com.dsk.common.core.domain.AjaxResult;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.utils.StringUtils;
import com.dsk.common.utils.file.FileUtils;
import com.dsk.common.utils.file.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
......@@ -30,90 +30,87 @@ import java.util.stream.Collectors;
@RequestMapping("/business/file")
public class BusinessFileController extends BaseController {
// @Autowired
// private ServerConfig serverConfig;
//
// /**
// * 新建文件夹
// */
//// @PreAuthorize("@ss.hasPermi('system:file:add')")
//// @Log(title = "项目资料文档", businessType = BusinessType.INSERT)
// @PostMapping("/new")
// public AjaxResult newFolder(@RequestBody(required=false) BusinessIdDto filePath) {
// return FileUtils.newFolder(filePath.getFilePath()) ? AjaxResult.success() : AjaxResult.error();
// }
//
// /**
// * 删除某个文件或整个文件夹
// */
// @PostMapping("/remove")
// public AjaxResult removeFile(@RequestBody(required=false) BusinessIdDto filePath) {
// return FileUtils.delFolder(filePath.getFilePath()) ? AjaxResult.success() : AjaxResult.error();
// }
//
// /**
// * 分页查询项目的所有文件
// * 获取文件夹中所有文件
// */
// @GetMapping(value = "/list")
// public TableDataInfo getAllFiles(BusinessIdDto filePath) {
// startPage();
// List<BusinessFileVo> allFiles;
// if(StringUtils.isNumeric(filePath.getFilePath())) filePath.setFilePath(ShuZhiHuaConfig.getProfile() + filePath.getFilePath());
// allFiles = FileUtils.getAllFiles(filePath.getFilePath());
// //模糊查询文件
// if(StringUtils.isNotEmpty(filePath.getKeyword())){
// List<BusinessFileVo> allFileName = FileUtils.getAllFileNames(filePath.getFilePath());
// allFiles = allFileName.stream().filter(p -> p.getFilePath().contains(filePath.getKeyword())).collect(Collectors.toList());
// }
// //文件按照时间倒序
// allFiles = allFiles.stream().sorted(Comparator.comparing(BusinessFileVo::getCreatTime).reversed()).collect(Collectors.toList());
// return getDataTable(allFiles);
// }
//
// /**
// * 上传文件及文件夹
// * @param file 文件流
// * @param request 请求头参数
// * @return
// */
// @PostMapping("/upload")
// public AjaxResult uploadFolder(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
// try {
// //获取文件名
// String filename = file.getOriginalFilename();
// String businessFileName = request.getHeader("FilePath");
// // 上传文件路径
// String filePath = ShuZhiHuaConfig.getUploadPath() + businessFileName + "/";
//
// //校验是否上传同名文件
// File newFile = new File(filePath);
// if (newFile.exists()) {
// // 获取当前目录下的文件和文件夹
// File[] files = newFile.listFiles();
// for (File allFile : files) {
// if (filename.equals(allFile.getName())) return error("文件已存在");
// }
// }
//
// // 上传并返回文件全路径
// String fileName = FileUploadUtils.upload(filePath, file);
//// String url = serverConfig.getUrl() + fileName;
// AjaxResult ajax = AjaxResult.success();
// ajax.put("url", fileName);
// return ajax;
// } catch (IOException e) {
// return AjaxResult.error(e.getMessage());
// }
// }
//
// /**
// * 下载文件
// * @param filePath 要下载的文件路径
// * @param response 返回的响应
// */
// @PostMapping("/download")
// public void downloadFolder(@RequestBody BusinessIdDto filePath, HttpServletResponse response) {
// FileUtils.downloadByFilePath(filePath.getFilePath(),response);
// }
/**
* 新建文件夹
*/
// @PreAuthorize("@ss.hasPermi('system:file:add')")
// @Log(title = "项目资料文档", businessType = BusinessType.INSERT)
@PostMapping("/new")
public AjaxResult newFolder(@RequestBody(required=false) BusinessIdDto filePath) {
return OldFileUtils.newFolder(filePath.getFilePath()) ? AjaxResult.success() : AjaxResult.error();
}
/**
* 删除某个文件或整个文件夹
*/
@PostMapping("/remove")
public AjaxResult removeFile(@RequestBody(required=false) BusinessIdDto filePath) {
return OldFileUtils.delFolder(filePath.getFilePath()) ? AjaxResult.success() : AjaxResult.error();
}
/**
* 分页查询项目的所有文件
* 获取文件夹中所有文件
*/
@GetMapping(value = "/list")
public TableDataInfo getAllFiles(BusinessIdDto filePath) {
List<BusinessFileVo> allFiles;
if(StringUtils.isNumeric(filePath.getFilePath())) filePath.setFilePath(FileUploadUtils.getDefaultBaseDir() + filePath.getFilePath());
allFiles = OldFileUtils.getAllFiles(filePath.getFilePath());
//模糊查询文件
if(StringUtils.isNotEmpty(filePath.getKeyword())){
List<BusinessFileVo> allFileName = OldFileUtils.getAllFileNames(filePath.getFilePath());
allFiles = allFileName.stream().filter(p -> p.getFilePath().contains(filePath.getKeyword())).collect(Collectors.toList());
}
//文件按照时间倒序
allFiles = allFiles.stream().sorted(Comparator.comparing(BusinessFileVo::getCreatTime).reversed()).collect(Collectors.toList());
return TableDataInfo.build(allFiles);
}
/**
* 上传文件及文件夹
* @param file 文件流
* @param request 请求头参数
* @return
*/
@PostMapping("/upload")
public AjaxResult uploadFolder(@RequestPart("file") MultipartFile file, HttpServletRequest request) {
try {
//获取文件名
String filename = file.getOriginalFilename();
String businessFileName = request.getHeader("FilePath");
// 上传文件路径
String filePath = FileUploadUtils.getDefaultBaseDir() + businessFileName + "/";
//校验是否上传同名文件
File newFile = new File(filePath);
if (newFile.exists()) {
// 获取当前目录下的文件和文件夹
File[] files = newFile.listFiles();
for (File allFile : files) {
if (filename.equals(allFile.getName())) return AjaxResult.error("文件已存在");
}
}
// 上传并返回文件全路径
String fileName = FileUploadUtils.upload(filePath, file);
// String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", fileName);
return ajax;
} catch (IOException e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 下载文件
* @param filePath 要下载的文件路径
* @param response 返回的响应
*/
@PostMapping("/download")
public void downloadFolder(@RequestBody BusinessIdDto filePath, HttpServletResponse response) {
OldFileUtils.downloadByFilePath(filePath.getFilePath(),response);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment