寫在前面
平常工作中的項目,上傳的文件一般都會傳到對象存儲云服務中。當接手一個小項目,如何自己動手搭建一個文件服務器,實現圖片、文件的回顯,可以通過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
,此時再拼上域名就可以訪問該文件了!