qa-prevention-gwj/src/main/java/com/zcloud/util/FileUploadUtil.java

69 lines
2.6 KiB
Java

package com.zcloud.util;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传工具类
* 变更文件上传方式,原上传方式可能会导致附件丢失
* 修改后逻辑:点击上传 -> 调后端接口返回临时文件路径 -> 提交-> 临时文件拷贝到正式,保存正式文件地址 -> 定期清空临时文件
* @date 2024-9-10
* @author hyx
* @version V1.0
*/
public class FileUploadUtil {
private final static String PATH_PREFIX = "/mnt/vdc1/qask/file"; //服务器路径前缀
private final static String TEMPORARY_FILE_PATH = "/uploadFiles/linshi/"; //临时文件储存路径
private final static String PRODUCT_FILE_PATH = "/uploadFiles/yhtp/"; //正式文件储存路径
/**
* 上传文件到服务器临时地址
*
* @param file 文件
* @param CORPINFO_ID 企业id
* @return 文件临时路径
* @throws Exception
* @date 2024-9-10
* @author hyx
*/
public static String uploadTemporaryFile(MultipartFile file,String CORPINFO_ID) throws Exception {
String ffile = DateUtil.getDays();
String fileName = UuidUtil.get32UUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
try {
Smb.sshSftp(file,fileName,TEMPORARY_FILE_PATH + CORPINFO_ID + "/" + ffile);
} catch (Exception e) {
throw new RuntimeException(e);
}
return TEMPORARY_FILE_PATH + CORPINFO_ID+ "/" + ffile + "/" + fileName;
}
/**
* 临时文件拷贝到正式
*
* @param temporaryFilePath 临时文件路径
* @param CORPINFO_ID 企业id
* @return 不含路径前缀的正式文件路径
* @throws Exception
* @date 2024-9-10
* @author hyx
*/
public static String copyTemporaryFileToProduct(String temporaryFilePath,String CORPINFO_ID) throws Exception {
//临时文件在服务器的完整路径
String completeTemporaryPath = PATH_PREFIX + temporaryFilePath;
//截取文件名
String fileName = completeTemporaryPath.substring(completeTemporaryPath.lastIndexOf("")).replace("/","");
//正式文件完整路径
String completeProductPath = PATH_PREFIX + PRODUCT_FILE_PATH + CORPINFO_ID + "/" + DateUtil.getDays() + "/";
//临时文件拷贝到正式路径
try {
FileUtil.copy(completeTemporaryPath,completeProductPath,true);
} catch (IORuntimeException e) {
throw new RuntimeException(e);
}
return PRODUCT_FILE_PATH + fileName;
}
}