Java-文件上传操作

文件上传借助于 org.springframework.web.multipart。

SpringBoot 文件上传配置

1
2
3
4
5
6
7
spring:
servlet:
multipart:
# 单个文件大小
max-file-size: 100MB
# 设置总上传的文件大小
max-request-size: 200MB

Contorller层中的上传接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Autowired
private ServerConfig serverConfig;

/**
* 通用上传请求
*/
@PostMapping("/upload")
public ResultJson uploadFile(MultipartFile file) throws Exception {
try {
// 上传文件路径(配置文件中配置的上传路径)
String filePath = MyConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
// 文件的请求路径(绝对路径)
String url = serverConfig.getUrl() + fileName;
// 构造返回给前台的json
Map<String, String> params = new HashMap<>(16);
params.put("fileName", fileName);
params.put("url", url);
return ResultJson.ok(params);
} catch (Exception e) {
return ResultJson.failure(ResultCode.BAD_REQUEST, e.getMessage());
}
}

上传工具类中的核心方法

上传方法

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
48
49
50
/**
* 根据文件路径上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @return 文件名称
* @throws IOException
*/
public static final String upload(String baseDir, MultipartFile file) throws IOException
{
try
{
return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
}
catch (Exception e)
{
throw new IOException(e.getMessage(), e);
}
}

/**
* 文件上传
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @param allowedExtension 上传文件类型
* @return 返回上传成功的文件名
* @throws FileSizeLimitExceededException 如果超出最大大小
* @throws FileNameLengthLimitExceededException 文件名太长
* @throws IOException 比如读写文件出错时
* @throws InvalidExtensionException 文件校验异常
*/
public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)
throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
InvalidExtensionException
{
int fileNameLength = file.getOriginalFilename().length();
if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
{
throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
}

// 文件大小和后缀校验,如果不合法会抛相应的异常
assertAllowed(file, allowedExtension);
String fileName = extractFileName(file);
File desc = getAbsoluteFile(baseDir, fileName);
file.transferTo(desc);
String pathFileName = getPathFileName(baseDir, fileName);
return pathFileName;
}

构造文件路径和请求路径

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
/**
* 编码文件名
*/
public static final String extractFileName(MultipartFile file)
{
String fileName;
String extension = getExtension(file);
//文件名形式:yyyy/MM/dd/<UUID>.<扩展名>
fileName = DateUtils.datePath() + "/" + IdUtils.fastUUID() + "." + extension;
return fileName;
}

/**
* 通过绝对路径创建空的目标文件
*/
private static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException
{
File desc = new File(uploadDir + File.separator + fileName);

if (!desc.getParentFile().exists())
{
desc.getParentFile().mkdirs();
}
if (!desc.exists())
{
desc.createNewFile();
}
return desc;
}

/**
* 构造文件请求的相对路径
*/
private static final String getPathFileName(String uploadDir, String fileName) {
int dirLastIndex = MyConfig.getProfile().length();
String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
// 构造请求文件资源的路径,避免给前台暴露服务器上文件的实际路径
String pathFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
return pathFileName;
}