商务网站模板,后台网站建设招聘,湖南seo优化,哪些项目适合开工作室文章目录 写在前面一、配置1、application.properties2、webMvc配置3、查看效果 二、文件上传 写在前面
平常工作中的项目#xff0c;上传的文件一般都会传到对象存储云服务中。当接手一个小项目#xff0c;如何自己动手搭建一个文件服务器#xff0c;实现图片、文件的回显… 文章目录 写在前面一、配置1、application.properties2、webMvc配置3、查看效果 二、文件上传 写在前面
平常工作中的项目上传的文件一般都会传到对象存储云服务中。当接手一个小项目如何自己动手搭建一个文件服务器实现图片、文件的回显可以通过http请求获取到呢 注本文以Springboot为基础在其web环境进行搭建的 一、配置
1、application.properties
local.file.dirD:/file/
local.file.path/data2、webMvc配置
Configuration
public class WebmvcConfigurer implements WebMvcConfigurer {Value(${local.file.dir})private String localFileDir;Value(${local.file.path})private String localFilePath;Overridepublic void addResourceHandlers(NotNull ResourceHandlerRegistry registry) {File file new File(localFileDir);if (file.exists() file.isFile()) {throw new RuntimeException(本地路径已被占用 localFileDir);}if(!file.exists()) {file.mkdirs();}registry.addResourceHandler(localFilePath /**).addResourceLocations(file: localFileDir);}注意此处的addResourceHandler是添加的我们访问时的路径addResourceLocations添加的是本地文件路径如果使用本地路径必须要加file:
3、查看效果
我们在D:/file/目录中存放一个aaa.jpg的文件访问localhost:8080/data/aaa.jpg就可以获取到这张图片了
二、文件上传
RestController
public class Controller {Value(${local.file.dir})private String localFileDir;Value(${local.file.path})private String localFilePath;PostMapping(/upload)public MapString, String uploadFile(RequestParam(file) MultipartFile file){MapString, String resultMap new HashMap();//获取上传文件的原始文件名String fileName file.getOriginalFilename();if(StringUtils.isBlank(fileName) || !fileName.contains(.)) {throw new RuntimeException(文件名有误);}// uuid生成文件String fileLastName fileName.substring(fileName.lastIndexOf(.));String localFileName UUID.randomUUID() fileLastName;//保存文件FileUtils.saveFile(file, localFileDir localFileName);// 拼文件名resultMap.put(url, localFilePath / localFileName);return resultMap;}
}
调用文件上传时会返回一个文件的url/data/aaa.jpg此时再拼上域名就可以访问该文件了