写在前面
平常工作中的项目,上传的文件一般都会传到对象存储云服务中。当接手一个小项目,如何自己动手搭建一个文件服务器,实现图片、文件的回显,可以通过http请求获取到呢?
注!本文以Springboot为基础,在其web环境进行搭建的
一、配置
1、application.properties
local.file.dir=D:/file/
local.file.path=/data
2、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 Map<String, String> uploadFile(@RequestParam("file") MultipartFile file){Map<String, 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
,此时再拼上域名就可以访问该文件了!