一、需求
在项目开发中,遇到需要将页面上的文件上传至本地保存,之后这个上传的文件还能进行访问,后台是Spring Boot框架搭建的,只需将文件上传至Spring Boot项目编译之后的classes\static\文件夹中即可。如下图:
二、文件上传
1、 定义文件上传接口方法
// 在pom.xml引入spring-boot-starter-web依赖,即可导包 import org.springframework.web.multipart.MultipartFile; // fileRoot:上传文件保存的根路径 String upload(MultipartFile file, String fileRoot) throws IOException;
2、文件上传接口方法实现
@Override
public String upload(MultipartFile file, String fileRoot) throws IOException {
prepareFilePath(fileRoot);
// 获取上传文件的原文件名
String fileName = file.getOriginalFilename();
// 规则化之后的文件上传根路径
String normalizeFileRoot = getNormalizeFileRoot(fileRoot);
// 根据路径和文件名创建目标文件
File targetFile = new File(normalizeFileRoot, fileName);
// 如果目标文件存在,删除
if (targetFile.exists())
targetFile.delete();
// 将目标文件进行转移
file.transferTo(targetFile);
return String.format("%s\\%s", normalizeFileRoot, fileName);
}
/**
fileRoot:上传文件保存的根路径
此方法是准备文件上传的路径,如果路径不存在,即创建
*/
private void prepareFilePath(String fileRoot) {
File file = new File(Helper.normalizePath(fileRoot));
if (!file.exists())
file.mkdirs();
}
/**
该方法主要对文件路径进行规则化,如:D:\\\360Browser\///360Chrome\\//,
像这种路径就不正确,此方法可以将路径规则化为:D:\360Browser\360Chrome
*/
private String getNormalizeFileRoot(String fileRoot) {
return Helper.normalizePath(fileRoot);
}
Helper工具类中的路径规则化方法
public static String normalizePath(String path) {
String result = path.replaceAll("/+", Matcher.quoteReplacement(File.separator));
return result.replaceAll("\\\\+", Matcher.quoteReplacement(File.separator));
}
3、Controller
@PostMapping("/upload")
public RequestResult upload(@RequestParam("file") MultipartFile file) throws IOException {
Config config = configService.get("Upload", "FileRoot");
String filePath = busService.upload(file, config.getValue());
return RequestResult.success(filePath);
}
三、测试
1、 使用Postman进行文件上传测试
2、 在浏览器中输入定位文件.doc,可以将文件下载到本地