本文是的入門項目,文件上傳、下載,利用、NIO等相關技術實現。學習文件上傳下載知識。對初學的同學會有一些幫助。
廢話不多說,直接上代碼。
初始化相關配置
筆者這里采用nacos作為配置中心,注解可以省去/。文件存儲的路徑。
@ConfigurationProperties(prefix = "file")
@Data
public class FileStoreProperties {
private String rootLocation;
}
使用@注解作為后置處理器,等初始化完成,初始化存儲文件路徑。
這里加"/"目的是為了使用絕對路徑,而不是相對路徑。
/**
* 初始化
*/
@Override
@PostConstruct
public void init() throws IOException {
rootPath = Paths.get("/", fileStoreProperties.getRootLocation());
if (Files.notExists(rootPath)) {
Files.createDirectories(rootPath);

}
}
文件上傳實現
接受瀏覽器請求、上傳文件到服務器(本文就是指的本地,有條件可以使用)。
層
必須使用POST請求上傳文件。
@PostMapping("/upload")
public String fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
fileStoreService.uploadFile(file);
return "success";
}
層
對傳過來的文件進行保存,如果文件為空則直接。
先根據根路徑獲取需要存儲到的位置,然后直接使用NIO拷貝文件。
@Override
public void uploadFile(MultipartFile file) throws IOException {
if (file.isEmpty()) {
return;
}

Path resolve = rootPath.resolve(file.getOriginalFilename()).normalize().toAbsolutePath();
Files.copy(file.getInputStream(), resolve, StandardCopyOption.REPLACE_EXISTING);
}
使用測試
上傳成功截圖
文件列表實現
接受瀏覽器的請求,返回當前服務器中存在的文件列表。
層實現
把找到的文件按照路徑返回。
@GetMapping("listAll")
public List listAll() throws IOException {
return fileStoreService.listAll().stream().map(path -> path.toFile().getName()).collect(Collectors.toList());
}
層實現
遍歷文件,深度為1層本地文件上傳到服務器,并且排除當前路徑,返回相對路徑
/**
* 文件遍歷

*/
@Override
public List listAll() throws IOException {
return Files.walk(rootPath, 1)
.filter(path -> !path.equals(rootPath))
.map(rootPath::relativize).collect(Collectors.toList());
}
測試
文件查詢調用截圖
下載單個文件
接受瀏覽器請求,根據文件名找到文件,并且返回給前端,這里涉及到瀏覽器的行為,不能返回JSON數據,對中需要設置type。
層實現
中的設置很關鍵本地文件上傳到服務器,是告訴瀏覽器要下載文件。
@GetMapping("/getFile")
public ResponseEntity getFile(@RequestParam("fileName") String fileName) throws MalformedURLException {
org.springframework.core.io.Resource oneByFileName = fileStoreService.findOneByFileName(fileName);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + oneByFileName.getFilename() + "\"")
.body(oneByFileName);

}
層實現
/**
* 獲取單個文件名
*
* @param fileName
* @return
* @throws MalformedURLException
*/
@Override
public Resource findOneByFileName(String fileName) throws MalformedURLException {
Path path = rootPath.resolve(fileName);
URI uri = path.toFile().toURI();
return new UrlResource(uri);
}
測試
下載文件
讓下載的文件
單個文件刪除
實現
@PostMapping("deleteOne")
public String deleteOne(@RequestParam("fileName") String fileName) throws IOException {
fileStoreService.deleteOne(fileName);
return "success";
}
層實現
@Override
public void deleteOne(String fileName) throws IOException {
Path resolve = rootPath.resolve(fileName);
Files.delete(resolve);
}
測試
刪除文件測試
其他配置
...max-file-size:
...max--size:
這就是使用進行上傳、下載文件的全部了,如果文中有不對的地方還請各位讀者指出,不盡感激。