Java任意类型文件上传通用接口

1、准备初始化一个Maven项目

2、添加配置

在bootstrap.yml

配置文件上传最大值

1
2
3
4
5
6
7
8
spring:
application:
name: commonApi
servlet:
multipart:
enabled: true
max-file-size: 64MB # 配置multipart上传单个文件最大位数
max-request-size: 640MB

3、创建Controller类

定义文件上传接口

接口参数说明:
area和dataType属于控制参数,可以控制上传的文件保存到服务器的某个目录。

directory参数是在上面参数配置的目录下创建新的子目录,比如数据是定时上传的,我们可以按时间创建一个子目录,按日期分组创建文件夹。

fileBinary参数是我们上传的文件流数据,包含了文件名称等信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ApiOperation(value = "通用文件上传接口", notes = "接口根据tdd配置的路径来查询要上传的地址,tdd里的配置路径会截取第一个$以前的内容并拼接上directory", response = Result.class, httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "area", value = "区域(common)", paramType = "query", dataType = "String", required = true),
@ApiImplicitParam(name = "dataType", value = "数据类型(pdfoutaddr)", paramType = "query", dataType = "String", required = true),
@ApiImplicitParam(name = "directory", value = "这个参数是要拼接到tdd配置的路径后面,指的是子目录", paramType = "query", dataType = "String", required = true),
@ApiImplicitParam(name = "fileBinary", value = "要上传的文件二进制流数据()", paramType = "query", dataType = "String", required = true)
})
@ApiOperationSupport(author = "庞欢腾")
@PostMapping("/uploading")
public Result<Boolean> uploading(
@RequestParam("fileBinary") MultipartFile fileBinary,
@RequestParam("area") String area,
@RequestParam("dataType") String dataType,
@RequestParam("directory") String directory) {
return wordToHtmlService.uploading(fileBinary, area, dataType, directory);
}

4、定义接口类并实现接口方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Override
public Result<Boolean> uploading(MultipartFile fileBinary, String area, String dataType, String directory) {

TDealdataDict tdd = tddRedisUtil.getTdd(area, dataType);
if (tdd == null) {
log.info("没有找到这个配置 area:" + area + " dataType:" + dataType);
return Result.failed("没有找到这个配置 area:" + area + " dataType:" + dataType);
}
// 读取上传路径
String filePath = tdd.getOrgPath();

if (fileBinary.isEmpty()) {
log.info("上传的文件为空!");
return Result.failed("上传的文件为空!");
}

if (OSNameUtil.isLinux()) {
if (!filePath.endsWith("/")) {
filePath += "/";
}
} else {
if (filePath.endsWith("\\")) {
filePath += "\\";
}
}

filePath = filePath + directory;

File exisfile = new File(filePath);
// 检测是否存在目录
if (!exisfile.exists()) {
exisfile.mkdirs();
}

// 文件名
String fileName = fileBinary.getOriginalFilename();
// 文件上传后的路径
File dest = new File(filePath + fileName);
log.info("文件路径为:"+filePath + fileName);
try {
fileBinary.transferTo(dest);
} catch (Exception e) {
log.info("上传异常!", e);
return Result.success(false);
}
return Result.success(true);
}