一、場景
Java實(shí)現(xiàn)文件上傳到服務(wù)器本地,并通過url訪問
有個(gè)需求,前端上傳文件,需要用開關(guān)的方式同時(shí)支持上傳七牛和服務(wù)器本地,方便不同的用戶需求合理分配資源。本篇主要介紹文件上傳到本地,然后通過url訪問。
二、SpringBoot默認(rèn)靜態(tài)資源訪問方式
首先想到的就是可以通過SpringBoot通常訪問靜態(tài)資源的方式,當(dāng)訪問:項(xiàng)目根路徑 + / + 靜態(tài)文件名時(shí),SpringBoot會依次去類路徑下的四個(gè)靜態(tài)資源目錄下查找(默認(rèn)配置)。
在資源文件resources目錄下建立如下四個(gè)目錄:
重啟Spring boot,訪問
http://localhost:8080/1.jpg
http://localhost:8080/2.jpg
http://localhost:8080/3.jpg
http://localhost:8080/4.jpg
結(jié)果:
三、上傳的文件應(yīng)該存儲在哪?怎么訪問?
1.文件存儲在哪?
前文所說外部用戶可通過url訪問服務(wù)器資源文件resources目錄下的靜態(tài)資源,但若是將上傳的文件都保存在resources相關(guān)目錄下,將會導(dǎo)致后續(xù)打包過大,程序和代碼不分離,無法查看等問題。
解決方案:文件上傳到服務(wù)器某個(gè)目錄,然后SpringBoot配置虛擬路徑,映射到此目錄。
2.怎么訪問?
通過WebMvcConfigurer 的addResourceHandlers將匹配上虛擬路徑的url映射到文件上傳到服務(wù)器的目錄,這樣就可以通過url來獲取服務(wù)器上的靜態(tài)資源了。
示例代碼
代碼倉庫github路徑
目標(biāo):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映射到文件上傳到服務(wù)器的目錄,獲取靜態(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";
//自己設(shè)置的目錄
private static final String fileDir = "fileStorage";
//上傳文件存放目錄 = 工作目錄絕對路徑 + 自己設(shè)置的目錄,也可以直接自己指定服務(wù)器目錄
//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 {
//校驗(yàn)文件后綴
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,得到:
文章來源:http://www.zghlxwxcb.cn/news/detail-780264.html
五、總結(jié)
其實(shí)這和最初的SpringBoot獲取靜態(tài)資源的方式又有點(diǎn)不一樣,針對url做攔截,實(shí)際上resources目錄下并沒有files這個(gè)文件夾,它只是一個(gè)虛擬路徑,通過映射轉(zhuǎn)發(fā)到文件夾上傳目錄,在該目錄下通過文件名去定位。
另外,如果有用nginx,也可以在其配置中設(shè)置轉(zhuǎn)發(fā)。文章來源地址http://www.zghlxwxcb.cn/news/detail-780264.html
到了這里,關(guān)于Java實(shí)現(xiàn)文件上傳到服務(wù)器本地,并通過url訪問的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!