网站内容管理系统 上传word(分布式文件系统使用本机存储来存放文件资源的核心实现过程? )
优采云 发布时间: 2022-03-14 21:17网站内容管理系统 上传word(分布式文件系统使用本机存储来存放文件资源的核心实现过程?
)
笔者拟为大家介绍分布式文件系统,用于存储应用程序的图片、word、excel、pdf等文件。在开始介绍分布式文件系统之前,先介绍一下使用本地存储来存储文件资源。
两者的核心实现过程是一样的:
一、回顾
服务器接收上传的目的是提供文件访问服务,那么对于SpringBoot来说,可以提供文件访问的静态资源目录有哪些呢?
classpath:/META-INF/resources/
classpath:/static/
classpath:/public/
classpath:/resources/
这是我们之前介绍给大家的。从这里我们可以看到,这里的静态资源都在classpath下。那么问题就来了:
二、文件上传目录自定义配置
如何解决上述问题?不要忘记,spring boot 为我们提供了使用 spring.resources.static-locations 配置自定义静态文件的位置。
web:
upload-path: D:/data/
spring:
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
web.upload-path
spring.resources.static-locations
三、文件上传的控制器实现
详情见代码注释
@RestController
public class FileUploadController {
//绑定文件上传路径到uploadPath
@Value("${web.upload-path}")
private String uploadPath;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultipartFile uploadFile,
HttpServletRequest request) {
// 在 uploadPath 文件夹中通过日期对上传的文件归类保存
// 比如:/2019/06/06/cf13891e-4b95-4000-81eb-b6d70ae44930.png
String format = sdf.format(new Date());
File folder = new File(uploadPath + format);
if (!folder.isDirectory()) {
folder.mkdirs();
}
// 对上传的文件重命名,避免文件重名
String oldName = uploadFile.getOriginalFilename();
String newName = UUID.randomUUID().toString()
+ oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
// 文件保存
uploadFile.transferTo(new File(folder, newName));
// 返回上传文件的访问路径
String filePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + format + newName;
return filePath;
} catch (IOException e) {
throw new CustomException(CustomExceptionType.SYSTEM_ERROR);
}
}
}
四、写一个模拟文件上传页面进行测试
将upload.html 文件放在classpath:public 目录中,以提供外部访问。
Title
访问测试,点击“选择文件”,然后保存
文件保存到服务器上web.upload-path指定的资源目录
浏览器端响应结果如下,返回一个文件HTTP访问路径:
使用这个HTTP访问路径,在浏览器端访问的效果如下。证明我们的文件已经成功上传到服务器了,以后如果需要访问图片,可以使用这个HTTP URL。