java本地文件上传
1、FileController
java
/**
* @author: yc
* @des: 文件接口
* @date: 2024/8/4 11:11
*/
@RestController
@RequestMapping("/file")
public class FileController {
@Resource
private FileService fileService;
@PostMapping("/upload")
public Response<List<Map<String,String>>> upload(@RequestPart("req") FileUploadReq req, @RequestPart("fileList") List<MultipartFile> fileList){
req.setFileList(fileList);
return Response.builder(fileService.upload(req));
}
}
2、FileService
java
/**
* @author: yc
* @des: 文件上传接口定义
* @date: 2024/8/3 10:04
*/
public interface FileService {
/**
* @author: yc
* @des: 文件上传到本地
* @date: 2024/8/3 10:05
*/
List<Map<String,String>> upload(FileUploadReq req);
}
3、FileServiceImpl
java
/**
* @author: yc
* @des: 文件存储接口实现
* @date: 2024/06/07 16:09
*/
@Service
public class ConfigFileStoreServiceImpl implements ConfigFileStoreService {
/**
* @author: yc
* @des: 文件上传
* @date: 2024/06/07 16:07
*/
@Override
public Result<List<FileAttributes>> uploadFiles(ReqBizCondition req) {
if(Objects.isNull(req)){
return Result.fail(RespBizCodeEnum.BIZ_10001.getCode(),"请求参数不能为空");
}
if(CollectionUtils.isEmpty(req.getFiles())){
return Result.fail(RespBizCodeEnum.BIZ_10001.getCode(),"文件不能为空");
}
if(StringUtils.isBlank(req.getModeType())){
return Result.fail(RespBizCodeEnum.BIZ_10001.getCode(),"前缀类型不能为空");
}
FilePixModeEnum e = EnumUtils.getValueOf(FilePixModeEnum.class, req.getModeType());
if(Objects.isNull(e)){
return Result.fail(RespBizCodeEnum.BIZ_10001.getCode(),"前缀类型错误");
}
List<FileAttributes> fileAttributesList = new ArrayList<>();
for(MultipartFile multipartFile : req.getFiles()){
Map<String, String> map = FileUtils.upload2local(multipartFile, req.getDataType(), req.getDataCode(), e);
FileAttributes fileAttributes = new FileAttributes();
fileAttributes.setFileName(map.get("fileName"));
fileAttributes.setFilePath(map.get("filePath"));
fileAttributes.setFileCategory(map.get("typeName"));
fileAttributes.setFileModel(map.get("subName"));
fileAttributes.setFileSize(Long.valueOf(map.get("fileSize")));
fileAttributes.setFileStatus(1);
fileAttributesList.add(fileAttributes);
}
return Result.data(fileAttributesList);
}
}
4、FileUploadReq
java
/**
* @author: yc
* @des: 文件上传请求
* @date: 2024/8/3 10:09
*/
@Data
public class FileUploadReq {
/**
* 前缀类型 默认不需要
* TIMESTAMP = '时间戳',UUID = '随机字符串',NONE = '无需前缀'
*/
private String pix = "NONE";
/**
* 文件
*/
private List<MultipartFile> fileList;
/**
* 一级文件夹名称 可选
*/
private String dirName1;
/**
* 二级文件夹名称 可选
*/
private String dirName2;
/**
* 是否需要年/月/日 子文件夹 默认不需要
*/
private Boolean needYMD = Boolean.FALSE;
}
5、FilePixModeEnum
java
/**
* @author: yc
* @des: 文件前缀模式枚举
* @date: 2024/06/07 16:24
*/
@Getter
@AllArgsConstructor
public enum FilePixModeEnum implements BaseEnum{
TIMESTAMP("TIMESTAMP","时间戳"),
UUID("UUID","随机字符串"),
NONE("NONE","无需前缀");
private String code;
private String name;
}