基于SpringBoot上传任意文件功能的实现

网友投稿 349 2023-04-24


基于SpringBoot上传任意文件功能的实现

一、pom文件依赖的添加

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-thymeleaf

二、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 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();

}

}

三、实现的service层

@Service

public class FileSystemStorageService implements StorageSuRfSmeYzWervice {

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 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

五、服务启动时的处理

六、测试成功的结果


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java 中 poi解析Excel文件版本问题解决办法
下一篇:谈谈对vue响应式数据更新的误解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~