package com.zzg.system.service.system.impl;
|
|
import cn.hutool.core.lang.Dict;
|
import cn.hutool.core.util.IdUtil;
|
import com.zzg.common.constant.SysConstants;
|
import com.zzg.common.exception.GlobalException;
|
import com.zzg.common.utils.DateUtil;
|
import com.zzg.common.utils.FileUtil;
|
import com.zzg.common.utils.ZZGFileUtil;
|
import com.zzg.system.domain.AttachFile;
|
import com.zzg.system.service.system.IFileService;
|
import lombok.NonNull;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.io.FileUtils;
|
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
import org.springframework.stereotype.Service;
|
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.web.multipart.MultipartFile;
|
|
import javax.servlet.http.HttpServletRequest;
|
import java.io.*;
|
import java.nio.file.Files;
|
import java.nio.file.Path;
|
import java.nio.file.Paths;
|
import java.util.*;
|
import java.util.function.Function;
|
import java.util.stream.Collectors;
|
|
@Service
|
@Slf4j
|
@EnableScheduling
|
public class FileServiceImpl implements IFileService {
|
|
@Value("${ruoyi.upload}")
|
private String uploadPath;
|
@Value("${ruoyi.temp}")
|
private String tempPath;
|
@Value("${ruoyi.template}")
|
private String template;
|
|
// @Resource
|
// DrawingsMapper drawingsMapper;
|
|
@Override
|
public void saveFile(@NonNull InputStream inputStream, @NonNull File file) {
|
try {
|
FileUtils.copyInputStreamToFile(inputStream, file);
|
} catch (IOException e) {
|
log.error("保存文件失败!!!", e);
|
throw new RuntimeException("文件保存失败", e);
|
}
|
}
|
|
@Override
|
public void saveFile(@NonNull InputStream inputStream, @NonNull String filename) {
|
saveFile(inputStream, new File(filename));
|
}
|
|
@Override
|
public String upload2Temp(@NonNull MultipartFile multipartFile, HttpServletRequest req) {
|
try {
|
// IE浏览器获取的"originalFileName"带盘符,此处不能直接用
|
String originalFileName = multipartFile.getOriginalFilename();
|
// 截取真实文件名,解决浏览器兼容性问题
|
String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
|
String path = tempPath + DateUtil.transDateToStr(new Date()) + "/" + IdUtil.fastSimpleUUID() + "/" + fileName;
|
saveFile(multipartFile.getInputStream(), path);
|
return path;
|
} catch (IOException e) {
|
log.error("保存文件失败!", e);
|
throw new RuntimeException("保存文件失败", e);
|
}
|
}
|
|
@Override
|
public List<Dict> upload2Temp(@NonNull List<MultipartFile> multipartFiles, HttpServletRequest req) {
|
Objects.requireNonNull(multipartFiles, "上传文件为空!");
|
// 文件保存方法
|
//此处文件已经保存
|
Function<MultipartFile, Dict> getInputStream = a -> {
|
long size = a.getSize();
|
if (size > 200 * 1024 * 1024) {
|
throw new RuntimeException("上传的单个文档不能大于200M");
|
}
|
String suffix = FileUtil.getSuffix(a.getOriginalFilename());
|
String[] suffixArray = {"shp", "cpg", "dbf", "prj", "sbn", "sbx", "xml", "shx"};
|
if (!Arrays.asList(suffixArray).contains(suffix)) {
|
// 将以上后缀名的文件都略过校验
|
try {
|
boolean b = FileUtil.CheckFileHead((FileInputStream) a.getInputStream());
|
if (!b) {
|
throw new RuntimeException("文件格式异常!");
|
}
|
} catch (IOException e) {
|
throw new RuntimeException("文件校验异常!", e);
|
}
|
}
|
|
// IE浏览器获取的"originalFileName"带盘符,此处不能直接用
|
String originalFileName = a.getOriginalFilename();
|
|
try {
|
Dict dict = new Dict();
|
// 截取真实文件名,解决浏览器兼容性问题
|
String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
|
String path = DateUtil.transDateToStr(new Date()) + "/" + ZZGFileUtil.getUUIDFileName(fileName);
|
saveFile(a.getInputStream(), tempPath + path);
|
dict.put("path", SysConstants.Path.TEMP + "/" + path);
|
dict.put("fileName", fileName);
|
return dict;
|
} catch (IOException e) {
|
throw new RuntimeException("获取上传文件输入流失败!", e);
|
}
|
};
|
|
// List<Dict> list = multipartFiles.parallelStream().map(getInputStream).collect(Collectors.toList());
|
// List<String> tempList = list.stream().map(new Function<String, String>() {
|
// @Override
|
// public String apply(String s) {
|
// s = SysConstants.Path.TEMP + "/" + s;
|
// return s;
|
// }
|
// }).collect(Collectors.toList());
|
|
return multipartFiles.parallelStream().map(getInputStream).collect(Collectors.toList());
|
}
|
|
|
@Override
|
public void moveFile(String sourcePath, String destPath) {
|
try {
|
sourcePath = tempPath + sourcePath;
|
destPath = uploadPath + destPath;
|
|
// 将字符串路径转换为Path对象
|
Path source = Paths.get(sourcePath);
|
Path dest = Paths.get(destPath);
|
// 确保目标目录存在,如果不存在则创建
|
if (!Files.exists(dest.getParent())) {
|
Files.createDirectories(dest.getParent());
|
}
|
|
// 将文件从源路径移动到目标路径
|
Files.move(source, dest);
|
} catch (IOException e) {
|
e.printStackTrace();
|
System.err.println("Failed to move file: " + e.getMessage());
|
}
|
}
|
|
@Override
|
public void deleteFile(String filePath) {
|
try {
|
filePath = uploadPath + filePath;
|
// 将字符串路径转换为Path对象
|
Path file = Paths.get(filePath);
|
// 如果文件存在,则删除它
|
if (Files.exists(file)) {
|
Files.delete(file);
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
@Override
|
public List<String> uploadFile2uploadPath(List<MultipartFile> fileList) {
|
Objects.requireNonNull(fileList, "上传文件为空!");
|
// 文件保存方法
|
//此处文件已经保存
|
Function<MultipartFile, String> getInputStream = a -> {
|
long size = a.getSize();
|
if (size > 20 * 1024 * 1024) {
|
throw new RuntimeException("上传的单个文档不能大于20M");
|
}
|
String suffix = FileUtil.getSuffix(a.getOriginalFilename());
|
String[] suffixArray = {"shp", "cpg", "dbf", "prj", "sbn", "sbx", "xml", "shx"};
|
if (!Arrays.asList(suffixArray).contains(suffix)) {
|
// 将以上后缀名的文件都略过校验
|
try {
|
boolean b = FileUtil.CheckFileHead((FileInputStream) a.getInputStream());
|
if (!b) {
|
throw new RuntimeException("文件格式异常!");
|
}
|
} catch (IOException e) {
|
throw new RuntimeException("文件校验异常!", e);
|
}
|
}
|
|
// IE浏览器获取的"originalFileName"带盘符,此处不能直接用
|
String originalFileName = a.getOriginalFilename();
|
try {
|
// 截取真实文件名,解决浏览器兼容性问题
|
String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
|
String path = ZZGFileUtil.getUUIDFileName(fileName);
|
saveFile(a.getInputStream(), uploadPath + path);
|
return path;
|
} catch (IOException e) {
|
throw new RuntimeException("获取上传文件输入流失败!", e);
|
}
|
};
|
|
List<String> list = fileList.parallelStream().map(getInputStream).collect(Collectors.toList());
|
|
List<String> filePathList = list.stream().map(new Function<String, String>() {
|
@Override
|
public String apply(String s) {
|
s = SysConstants.Path.UPLOAD + "/" + s;
|
return s;
|
}
|
}).collect(Collectors.toList());
|
return filePathList;
|
}
|
|
// @Override
|
// public List<String> uploadFile(List<MultipartFile> fileList) {
|
// Objects.requireNonNull(fileList, "上传文件为空!");
|
// // 文件保存方法
|
// //此处文件已经保存
|
// Function<MultipartFile, String> getInputStream = a -> {
|
//
|
// // IE浏览器获取的"originalFileName"带盘符,此处不能直接用
|
// String originalFileName = a.getOriginalFilename();
|
// try {
|
// // 截取真实文件名,解决浏览器兼容性问题
|
// String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
|
// String path = ZZGFileUtil.getUUIDFileName(fileName);
|
// saveFile(a.getInputStream(), uploadPath + path);
|
// return path;
|
// } catch (IOException e) {
|
// throw new RuntimeException("获取上传文件输入流失败!", e);
|
// }
|
// };
|
//
|
// List<String> list = fileList.parallelStream().map(getInputStream).collect(Collectors.toList());
|
//
|
// List<String> filePathList = list.stream().map(new Function<String, String>() {
|
// @Override
|
// public String apply(String s) {
|
// s = SysConstants.Path.UPLOAD + "/" + s;
|
// return s;
|
// }
|
// }).collect(Collectors.toList());
|
// return filePathList;
|
// }
|
|
// @Override
|
// public void downloadFile(@NonNull List<String> fileNames) throws IOException {
|
|
|
// if (fileNames.isEmpty()) {
|
// throw new RequestException("至少下载一个文件!");
|
// }
|
// // 根据文件路径前缀,拼接真实路径
|
// Function<String, String> judgeCatalogue = str -> {
|
// String identity = str.substring(0, str.indexOf("/"));
|
// boolean b = RegExpValidatorUtils.isDate(identity);
|
// if (b) {
|
// str = tempPath + str;
|
// }else {
|
// str = uploadPath + str;
|
// }
|
// return str;
|
// };
|
// List<String> fileNames_judege = fileNames.stream().map(judgeCatalogue).collect(Collectors.toList());
|
// if (1 == fileNames.size()) {
|
// ZZGFileUtil.outFile(new File(fileNames_judege.get(0)), fileNames_judege.get(0));
|
// } else {
|
// HttpServletResponse response = RequestHolder.getResponse();
|
// ZZGFileUtil.setOutFileHeader(response, fileNames_judege.get(0) + ".zip", null);
|
// ZipOutputStream outputStream = new ZipOutputStream(response.getOutputStream());
|
// ZZGFileUtil.copyZipOut(outputStream,
|
// fileNames_judege.stream().map(a -> a).map(File::new).toArray(File[]::new));
|
// outputStream.finish();
|
// }
|
// }
|
|
/**
|
* 单个文件下载
|
*
|
* @param filePath 文件绝对路
|
*/
|
// public void download(String filePath, HttpServletResponse response) throws IOException {
|
// File absFile = new File(filePath);
|
// if (absFile.exists()) {
|
// response.setContentType("application/octet-stream;charset=utf-8");
|
// response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(cn.hutool.core.io.FileUtil.getName(absFile), "UTF-8"));
|
// FileInputStream fileInputStream = new FileInputStream(absFile);
|
// int len = 0;
|
// byte[] buffer = new byte[1024];
|
// OutputStream outputStream = response.getOutputStream();
|
// while ((len = fileInputStream.read(buffer)) > 0) {
|
// outputStream.write(buffer, 0, len);
|
// }
|
// fileInputStream.close();
|
// outputStream.flush();
|
// outputStream.close();
|
// } else {
|
// throw new CustomException(CustomExceptionEnums.FILES_NOT_FOUND_ERROR);
|
// }
|
// }
|
|
|
/**
|
* 将指定文件从临时目录复制到持久目录
|
*
|
* @throws IOException
|
*/
|
@Override
|
public void synFiles(@NonNull List<String> fileNames, @NonNull String destDir) throws IOException {
|
List<File> files = fileNames.stream().map(File::new).collect(Collectors.toList());
|
File destFile = new File(destDir);
|
if (!destFile.exists()) {
|
boolean bool = destFile.mkdirs();
|
if (!destFile.isDirectory() || !bool) {
|
throw new IllegalAccessError("目录:" + destDir + "创建失败!");
|
}
|
}
|
FileUtils.copyToDirectory(files, destFile);
|
}
|
|
/**
|
* 将选择的文件同步到upload路径下
|
*
|
* @param fileNames 文件
|
* @throws IOException
|
*/
|
@Override
|
public void synFiles2Upload(List<String> fileNames) throws IOException {
|
File destFile = new File(uploadPath);
|
if (!destFile.exists()) {
|
boolean bool = destFile.mkdirs();
|
if (!destFile.isDirectory() || !bool) {
|
throw new IllegalAccessError("目录:" + uploadPath + "创建失败!");
|
}
|
}
|
// List<File> files = fileNames.stream().map(File::new).collect(Collectors.toList());
|
List<File> files = new ArrayList<>();
|
for (String path : fileNames) {
|
if (!path.contains(uploadPath)) {
|
files.add(new File(path));
|
}
|
}
|
if (files.size() > 0) {
|
FileUtils.copyToDirectory(files, destFile);
|
}
|
}
|
|
|
/**
|
* 将选择的文件同步到upload路径下(去除日期)
|
*
|
* @param fileNames 文件
|
* @throws IOException
|
*/
|
@Override
|
public List<File> synFiles2UploadMoveDate(List<String> fileNames) throws IOException {
|
File destFile = new File(uploadPath);
|
if (!destFile.exists()) {
|
boolean bool = destFile.mkdirs();
|
if (!destFile.isDirectory() || !bool) {
|
throw new IllegalAccessError("目录:" + uploadPath + "创建失败!");
|
}
|
}
|
// List<File> files = fileNames.stream().map(File::new).collect(Collectors.toList());
|
List<File> files = new ArrayList<>();
|
for (String path : fileNames) {
|
String sourcePath = path;
|
String separator = File.separator;
|
path = path.replace("\\", separator);
|
path = path.replace("/", separator);
|
// 获取 `\` 和 `_` 之间的字符串
|
int startIndex = path.lastIndexOf(File.separator) + 1;
|
int endIndex = path.indexOf("_");
|
String result = path.substring(startIndex, endIndex + 1);
|
|
// 删除文件名前面的自定义uuid
|
String targetPath = path.replace(result, "");
|
|
// 文件复制
|
try {
|
FileUtil.copy(sourcePath, targetPath);
|
} catch (Exception e) {
|
throw new RuntimeException(e);
|
}
|
|
if (!targetPath.contains(destFile.getAbsolutePath())) {
|
files.add(new File(targetPath));
|
}
|
}
|
|
if (files.size() > 0) {
|
FileUtils.copyToDirectory(files, destFile);
|
}
|
return files;
|
}
|
|
@Override
|
public void synFiles2Upload(Map<String, String> fileNames) throws IOException {
|
File destFile = new File(uploadPath);
|
if (!destFile.exists()) {
|
boolean bool = destFile.mkdirs();
|
if (!destFile.isDirectory() || !bool) {
|
throw new IllegalAccessError("目录:" + uploadPath + "创建失败!");
|
}
|
}
|
List<File> files = new ArrayList<>();
|
for (Map.Entry<String, String> e : fileNames.entrySet()) {
|
if (!e.getValue().contains(destFile.getAbsolutePath())) {
|
files.add(new File(e.getValue()));
|
}
|
}
|
if (files.size() > 0) {
|
FileUtils.copyToDirectory(files, destFile);
|
}
|
}
|
|
/**
|
* 保存文件目录的创建!
|
*/
|
// @PostConstruct
|
// public void createFilepath() {
|
// File file = new File(uploadPath);
|
// if (!file.exists()) {
|
// file.mkdirs();
|
// if (!file.isDirectory()) {
|
// throw new IllegalAccessError("系统保存文件的位置应该是一个可创建的目录!目录:" + uploadPath + "创建失败!");
|
// }
|
// }
|
// File file2 = new File(tempPath);
|
// if (!file2.exists()) {
|
// file2.mkdirs();
|
// if (!file2.isDirectory()) {
|
// throw new IllegalAccessError("系统保存文件的位置应该是一个可创建的目录!目录:" + tempPath + "创建失败!");
|
// }
|
// }
|
// }
|
|
/**
|
* 每天晚上12:00删除临时目录里面的过期文件,保存最近七天的文件
|
* <p>
|
*/
|
/*@Scheduled(cron = "00 00 00 * * ?")
|
@Override
|
public void refreshTemp() {
|
// File tempFile = new File(tempPath);
|
// // 获取临时目录中的所有文件夹
|
// Collection<File> listFilesAndDirs = FileUtils.listFilesAndDirs(tempFile, FalseFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
|
// // 排除临时目录自身
|
// listFilesAndDirs.remove(tempFile);
|
// for (File file : listFilesAndDirs) {
|
// if (DateUtil.daysBetween(DateUtil.transStrToDate(file.getName()), new Date()) > 7) {
|
// log.info("定时删除临时文件夹:" + file.getAbsolutePath());
|
// FileUtils.deleteQuietly(file);
|
// }
|
// }
|
// }
|
|
}*/
|
|
/*@Override
|
public String upload2Word(List<MultipartFile> multipartFiles, HttpServletRequest req) {
|
Objects.requireNonNull(multipartFiles, "上传文件为空!");
|
// 文件保存方法
|
//此处文件已经保存
|
Function<MultipartFile, String> getInputStream = a -> {
|
try {
|
// IE浏览器获取的"originalFileName"带盘符,此处不能直接用
|
String originalFileName = a.getOriginalFilename();
|
// 截取真实文件名,解决浏览器兼容性问题
|
String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
|
String path = DateUtil.transDateToStr(new Date()) + "/" + ZZGFileUtil.getUUIDFileName(fileName);
|
saveFile(a.getInputStream(), tempPath + path);
|
return path;
|
} catch (IOException e) {
|
throw new RuntimeException("获取上传文件输入流失败!", e);
|
}
|
};
|
// List<String> collect = multipartFiles.parallelStream().map(MultipartFile::getOriginalFilename).collect(Collectors.toList());
|
|
List<String> list = multipartFiles.parallelStream().map(getInputStream).collect(Collectors.toList());
|
|
|
List<String> tempList = list.stream().map(new Function<String, String>() {
|
@Override
|
public String apply(String s) {
|
s = SysConstants.Path.TEMP + "/" + s;
|
String last = s.substring(s.lastIndexOf(".") + 1);
|
if (last.equals("doc") || last.equals("docx")) {
|
s = wordService.wordToPdf(s);
|
}
|
return s;
|
}
|
}).collect(Collectors.toList());
|
|
return JSONArray.toJSONString(tempList);
|
}*/
|
@Override
|
@Transactional(rollbackFor = Exception.class)
|
public Integer uploadTemplateFile(String projectId, Integer noticeType, MultipartFile multipartFile) {
|
// File tempPath = new File(template);
|
// if (!tempPath.exists()) {
|
// tempPath.mkdirs();
|
// }
|
// String originalFileName = multipartFile.getOriginalFilename();
|
// String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
|
// String file = ZZGFileUtil.getUUIDFileName(fileName);
|
// try {
|
// FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(tempPath + File.separator + file));
|
// } catch (IOException e) {
|
// throw new RuntimeException(e);
|
// }
|
// //查询是否已有此模板数据
|
// Drawings drawings = drawingsMapper.selectOne(new LambdaQueryWrapper<Drawings>()
|
// .eq(Drawings::getProjectId, projectId)
|
// .eq(Drawings::getImageType, "公告模板")
|
// .eq(Drawings::getImagePersona, noticeType));
|
//
|
// if (drawings == null) {
|
// drawings = new Drawings();
|
// drawings.setProjectId(projectId);
|
// drawings.setImageType("公告模板");
|
// drawings.setImagePersona(noticeType.toString());
|
// drawings.setCreateTime(new Date());
|
// drawings.setCreateName(SecurityUtils.getUsername());
|
// }
|
// drawings.setUrl("template" + File.separator + file);
|
// drawings.setOriginal(originalFileName);
|
//
|
// int a;
|
// if (drawings.getId() != null) {
|
// a = drawingsMapper.updateById(drawings);
|
// } else {
|
// a = drawingsMapper.insert(drawings);
|
// }
|
return 1;
|
}
|
|
@Override
|
public void upload2uploadPath(List<AttachFile> familyAttachFiles) {
|
for (AttachFile attachFile : familyAttachFiles) {
|
String filePath = attachFile.getFilePath();
|
try {
|
FileInputStream file = new FileInputStream(filePath);
|
String path = uploadPath + "/" + IdUtil.fastSimpleUUID() + "_" + filePath.substring(filePath.lastIndexOf("/") + 1);
|
saveFile(file, path);
|
//更新路径
|
attachFile.setFilePath(path);
|
} catch (FileNotFoundException e) {
|
throw new GlobalException("文件不存在!");
|
} catch (IOException e) {
|
log.error("保存文件失败!", e);
|
throw new RuntimeException("保存文件失败", e);
|
}
|
}
|
}
|
|
|
/**
|
* 获取模板文件的真实路径
|
*
|
* @return 模板文件真实路径
|
*/
|
public String getTemplateFilePath() {
|
return template;
|
}
|
|
/**
|
* 获取临时文件的真实路径
|
*
|
* @return 模板文件真实路径
|
*/
|
public String getTempFilePath() {
|
return tempPath;
|
}
|
|
/**
|
* 获取下载文件的真实路径
|
*
|
* @return 模板文件真实路径
|
*/
|
public String getUploadFilePath() {
|
return uploadPath;
|
}
|
|
|
}
|