基于SpringBoot上傳任意文件功能的實現(xiàn)
一、pom文件依賴的添加
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
二、controller層
@Controller
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
//展示上傳過的文件
@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {
model.addAttribute("files", storageService.loadAll().map(path ->
MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
.build().toString())
.collect(Collectors.toList()));
return "uploadForm";
}
//下載選定的上傳的文件
@GetMapping("/files/{filename:.+}")
@ResponseBody
public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
Resource file = storageService.loadAsResource(filename);
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")
.body(file);
}
//上傳文件
@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
@ExceptionHandler(StorageFileNotFoundException.class)
public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
return ResponseEntity.notFound().build();
}
}
三、實現(xiàn)的service層
@Service
public class FileSystemStorageService implements StorageService {
private final Path rootLocation;
@Autowired
public FileSystemStorageService(StorageProperties properties) {
this.rootLocation = Paths.get(properties.getLocation());
}
@Override
public void store(MultipartFile file) {
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (IOException e) {
throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
}
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename) {
return rootLocation.resolve(filename);
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if(resource.exists() || resource.isReadable()) {
return resource;
}
else {
throw new StorageFileNotFoundException("Could not read file: " + filename);
}
} catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
@Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
@Override
public void init() {
try {
Files.createDirectory(rootLocation);
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
四、在application.properties文件上配置上傳的屬性
spring.http.multipart.max-file-size=128KB
spring.http.multipart.max-request-size=128KB
五、服務(wù)啟動時的處理

六、測試成功的結(jié)果

以上這篇基于SpringBoot上傳任意文件功能的實現(xiàn)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 詳解SpringBoot文件上傳下載和多文件上傳(圖文)
- springboot實現(xiàn)文件上傳和下載功能
- SpringBoot實現(xiàn)文件上傳下載功能小結(jié)
- springboot 文件上傳大小配置的方法
- SpringBoot限制文件或圖片上傳大小的兩種配置方法
- SpringBoot文件上傳控制及Java 獲取和判斷文件頭信息
- 全面解析SpringBoot文件上傳功能
- Springboot上傳excel并將表格數(shù)據(jù)導入或更新mySql數(shù)據(jù)庫的過程
- SpringBoot 文件上傳和下載的實現(xiàn)源碼
- SpringBoot+fileUpload獲取文件上傳進度
相關(guān)文章
Java?Stream實現(xiàn)多字段分組groupingBy操作詳解
Stream是Java8的一個新特性,主要用戶集合數(shù)據(jù)的處理,如排序、過濾、去重等等功能,本文就來講講如何利用Stream實現(xiàn)比較優(yōu)雅的按多字段進行分組groupingBy吧2023-06-06
基于Spring?Boot的線程池監(jiān)控問題及解決方案
這篇文章主要介紹了基于Spring?Boot的線程池監(jiān)控方案,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
詳解Servlet3.0新特性(從注解配置到websocket編程)
Servlet3.0的出現(xiàn)是servlet史上最大的變革,其中的許多新特性大大的簡化了web應用的開發(fā),為廣大勞苦的程序員減輕了壓力,提高了web開發(fā)的效率。2017-04-04
詳解JDK 5 Annotation 注解之@Target的用法介紹
這篇文章主要介紹了詳解JDK 5 Annotation 注解之@Target的用法介紹,需要的朋友可以參考下2016-02-02

