java本地文件上传
1、FileController
@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
public interface FileService {
List<Map<String,String>> upload(FileUploadReq req);
}
3、FileServiceImpl
@Service
public class ConfigFileStoreServiceImpl implements ConfigFileStoreService {
@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
@Data
public class FileUploadReq {
private String pix = "NONE";
private List<MultipartFile> fileList;
private String dirName1;
private String dirName2;
private Boolean needYMD = Boolean.FALSE;
}
5、FilePixModeEnum
@Getter
@AllArgsConstructor
public enum FilePixModeEnum implements BaseEnum{
TIMESTAMP("TIMESTAMP","时间戳"),
UUID("UUID","随机字符串"),
NONE("NONE","无需前缀");
private String code;
private String name;
}
6、EnumUtils
枚举工具类
7、FileUtils
文件工具类
8、结果截图
8.1 postman
8.2结果