Java實現(xiàn)文件上傳到服務器本地并通過url訪問的方法步驟
一、場景
Java實現(xiàn)文件上傳到服務器本地,并通過url訪問
有個需求,前端上傳文件,需要用開關(guān)的方式同時支持上傳七牛和服務器本地,方便不同的用戶需求合理分配資源。本篇主要介紹文件上傳到本地,然后通過url訪問。
二、SpringBoot默認靜態(tài)資源訪問方式
首先想到的就是可以通過SpringBoot通常訪問靜態(tài)資源的方式,當訪問:項目根路徑 + / + 靜態(tài)文件名時,SpringBoot會依次去類路徑下的四個靜態(tài)資源目錄下查找(默認配置)。

在資源文件resources目錄下建立如下四個目錄:

重啟Spring boot,訪問
http://localhost:8080/1.jpg
http://localhost:8080/2.jpg
http://localhost:8080/3.jpg
http://localhost:8080/4.jpg
結(jié)果:

三、上傳的文件應該存儲在哪?怎么訪問?
1.文件存儲在哪?
前文所說外部用戶可通過url訪問服務器資源文件resources目錄下的靜態(tài)資源,但若是將上傳的文件都保存在resources相關(guān)目錄下,將會導致后續(xù)打包過大,程序和代碼不分離,無法查看等問題。
解決方案:文件上傳到服務器某個目錄,然后SpringBoot配置虛擬路徑,映射到此目錄。
2.怎么訪問?
通過WebMvcConfigurer 的addResourceHandlers將匹配上虛擬路徑的url映射到文件上傳到服務器的目錄,這樣就可以通過url來獲取服務器上的靜態(tài)資源了。
示例代碼
目標:windows本地測試,將文件上傳到 D:\develop\work\project\myblog\myblog-file-upload\fileStorage 目錄下,然后通過http://localhost:8080/files/文件名 訪問。
配置類
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
FileServiceImpl fileService;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//將匹配上/files/**虛擬路徑的url映射到文件上傳到服務器的目錄,獲取靜態(tài)資源
registry.addResourceHandler("/" + fileService.pathPattern + "/**").addResourceLocations("file:" + fileService.filePath);
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
Controller
@RestController
@RequestMapping("/file")
public class FileController {
@Autowired
private FileServiceImpl fileService;
@PostMapping("/upload")
public FileUploadResponse upload(@RequestParam("file") MultipartFile file) {
return fileService.upload(file);
}
}
上傳文件目錄創(chuàng)建好后,主要通過 file.transferTo(new File(absolutePath)) 完成。
Service
@Slf4j
@Service
public class FileServiceImpl {
//攔截的url,虛擬路徑
public String pathPattern = "files";
//自己設置的目錄
private static final String fileDir = "fileStorage";
//上傳文件存放目錄 = 工作目錄絕對路徑 + 自己設置的目錄,也可以直接自己指定服務器目錄
//windows本地測試
//絕對路徑: D:\develop\work\project\myblog\myblog-file-upload\fileStorage\202302021010345680.jpg
//System.getProperty("user.dir") D:\develop\work\project\myblog\myblog-file-upload
//fileDir fileStorage
//fileName 202302021010345680.jpg
public String filePath = System.getProperty("user.dir") + File.separator + fileDir + File.separator;
private static final AtomicInteger SUFFIX = new AtomicInteger(0);
@Value(value = "${file.upload.suffix:jpg,jpeg,png,bmp,xls,xlsx,pdf}")
private String fileUploadSuffix;
public FileUploadResponse upload(MultipartFile file) {
FileUploadResponse result = new FileUploadResponse();
if (file.isEmpty()) {
log.error("the file to be uploaded is empty");
return result;
}
List<String> suffixList = Lists.newArrayList(fileUploadSuffix.split(","));
try {
//校驗文件后綴
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
if (!suffixList.contains(suffix)) {
log.error("unsupported file format");
return result;
}
//首次需生成目錄
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdirs();
}
String fileName = timeFormat(System.currentTimeMillis()) + SUFFIX.getAndIncrement() + "." + suffix;
String absolutePath = filePath + fileName;
log.info("absolutePath is {}", absolutePath);
file.transferTo(new File(absolutePath));
String separator = "/";
String path = separator + pathPattern + separator + fileName;
result.setPath(path);
result.setFileName(fileName);
} catch (Exception e) {
log.error("the file upload error occurred. e ", e);
}
return result;
}
public static String timeFormat(Long time) {
if (Objects.isNull(time)) {
return null;
}
DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return sdf.format(time);
}
}四、測試

查看文件夾,已上傳成功

將上傳接口返回的path拼接上域名或者ip端口、訪問 http://localhost:8080/files/202302021010345680.jpg,得到:

五、總結(jié)
其實這和最初的SpringBoot獲取靜態(tài)資源的方式又有點不一樣,針對url做攔截,實際上resources目錄下并沒有files這個文件夾,它只是一個虛擬路徑,通過映射轉(zhuǎn)發(fā)到文件夾上傳目錄,在該目錄下通過文件名去定位。
另外,如果有用nginx,也可以在其配置中設置轉(zhuǎn)發(fā)。
到此這篇關(guān)于Java實現(xiàn)文件上傳到服務器本地并通過url訪問的文章就介紹到這了,更多相關(guān)Java文件上傳到服務器本地并訪問內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot+WebSocket實現(xiàn)多人在線聊天案例實例
本文主要介紹了SpringBoot+WebSocket實現(xiàn)多人在線聊天案例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
關(guān)于maven全局配置文件settings.xml解析
這篇文章主要介紹了關(guān)于maven全局配置文件settings.xml,具有很好的參考價值,希望對大家有所幫助。2022-03-03
Spring Cloud 專題之Sleuth 服務跟蹤實現(xiàn)方法
這篇文章主要介紹了Spring Cloud 專題之Sleuth 服務跟蹤,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08

