一、pom文件依赖的添加
  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-test</artifactId>
  10. <scope>test</scope>
  11. </dependency>
  12.  
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  16. </dependency>
  17. </dependencies>
二、controller层
  1. @Controller
  2. public class FileUploadController {
  3. private final StorageService storageService;
  4.  
  5. @Autowired
  6. public FileUploadController(StorageService storageService) {
  7. this.storageService = storageService;
  8. }
  9.  
  10. //展示上传过的文件
  11. @GetMapping("/")
  12. public String listUploadedFiles(Model model) throws IOException {
  13.  
  14. model.addAttribute("files", storageService.loadAll().map(path ->
  15. MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
  16. .build().toString())
  17. .collect(Collectors.toList()));
  18.  
  19. return "uploadForm";
  20. }
  21.  
  22. //下载选定的上传的文件
  23. @GetMapping("/files/{filename:.+}")
  24. @ResponseBody
  25. public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
  26.  
  27. Resource file = storageService.loadAsResource(filename);
  28. return ResponseEntity
  29. .ok()
  30. .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFilename()+"\"")
  31. .body(file);
  32. }
  33.  
  34. //上传文件
  35. @PostMapping("/")
  36. public String handleFileUpload(@RequestParam("file") MultipartFile file,
  37. RedirectAttributes redirectAttributes) {
  38.  
  39. storageService.store(file);
  40. redirectAttributes.addFlashAttribute("message",
  41. "You successfully uploaded " + file.getOriginalFilename() + "!");
  42.  
  43. return "redirect:/";
  44. }
  45.  
  46. @ExceptionHandler(StorageFileNotFoundException.class)
  47. public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
  48. return ResponseEntity.notFound().build();
  49. }
  50. }
三、实现的service层
  1. @Service
  2. public class FileSystemStorageService implements StorageService {
  3.  
  4. private final Path rootLocation;
  5.  
  6. @Autowired
  7. public FileSystemStorageService(StorageProperties properties) {
  8. this.rootLocation = Paths.get(properties.getLocation());
  9. }
  10.  
  11. @Override
  12. public void store(MultipartFile file) {
  13. try {
  14. if (file.isEmpty()) {
  15. throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
  16. }
  17. Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
  18. } catch (IOException e) {
  19. throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
  20. }
  21. }
  22.  
  23. @Override
  24. public Stream<Path> loadAll() {
  25. try {
  26. return Files.walk(this.rootLocation, )
  27. .filter(path -> !path.equals(this.rootLocation))
  28. .map(path -> this.rootLocation.relativize(path));
  29. } catch (IOException e) {
  30. throw new StorageException("Failed to read stored files", e);
  31. }
  32.  
  33. }
  34.  
  35. @Override
  36. public Path load(String filename) {
  37. return rootLocation.resolve(filename);
  38. }
  39.  
  40. @Override
  41. public Resource loadAsResource(String filename) {
  42. try {
  43. Path file = load(filename);
  44. Resource resource = new UrlResource(file.toUri());
  45. if(resource.exists() || resource.isReadable()) {
  46. return resource;
  47. }
  48. else {
  49. throw new StorageFileNotFoundException("Could not read file: " + filename);
  50.  
  51. }
  52. } catch (MalformedURLException e) {
  53. throw new StorageFileNotFoundException("Could not read file: " + filename, e);
  54. }
  55. }
  56.  
  57. @Override
  58. public void deleteAll() {
  59. FileSystemUtils.deleteRecursively(rootLocation.toFile());
  60. }
  61.  
  62. @Override
  63. public void init() {
  64. try {
  65. Files.createDirectory(rootLocation);
  66. } catch (IOException e) {
  67. throw new StorageException("Could not initialize storage", e);
  68. }
  69. }
  70. }
四、在application.properties文件上配置上传的属性

  1. spring.http.multipart.max-file-size=128KB
  2. spring.http.multipart.max-request-size=128KB
五、服务启动时的处理

六、测试成功的结果
 
 

 

SpringBoot上传任意文件功能的实现的更多相关文章

  1. Springboot 上传CSV文件并将数据存入数据库

    .xml文件依赖配置 <!--csv依赖 --> <dependency> <groupId>org.apache.commons</groupId> ...

  2. springboot上传下载文件

    在yml配置相关内容 spring: # mvc: throw-exception-if-no-handler-found: true #静态资源 static-path-pattern: /** r ...

  3. 解决springBoot上传大文件异常问题

    上传文件过大时的报错: org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size ex ...

  4. springboot上传linux文件无法浏览,提示404错误

    1.配置文件地址置换 @Componentclass WebConfigurer implements WebMvcConfigurer { @Autowired ConfigUtil bootdoC ...

  5. 【WCF】利用WCF实现上传下载文件服务

    引言     前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...

  6. WebSSH画龙点睛之lrzsz上传下载文件

    本篇文章没有太多的源码,主要讲一下实现思路和技术原理 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过lrzsz来完成的,主要是因为其简单方便,不需要额外打开sftp之 ...

  7. springboot整合ueditor实现图片上传和文件上传功能

    springboot整合ueditor实现图片上传和文件上传功能 写在前面: 在阅读本篇之前,请先按照我的这篇随笔完成对ueditor的前期配置工作: springboot+layui 整合百度富文本 ...

  8. WEB安全第二篇--用文件搞定服务器:任意文件上传、文件包含与任意目录文件遍历

    零.前言 最近做专心web安全有一段时间了,但是目测后面的活会有些复杂,涉及到更多的中间件.底层安全.漏洞研究与安全建设等越来越复杂的东东,所以在这里想写一个系列关于web安全基础以及一些讨巧的pay ...

  9. PHP中使用Session配合Javascript实现文件上传进度条功能

    Web应用中常需要提供文件上传的功能.典型的场景包括用户头像上传.相册图片上传等.当需要上传的文件比较大的时候,提供一个显示上传进度的进度条就很有必要了. 在PHP .4以前,实现这样的进度条并不容易 ...

随机推荐

  1. 对jsp的初步了解及规范问题(二)

    前言 今天的例子是用jsp制作简单的“艾宾浩斯记忆曲线的学习计划表”. 重点不是算法,重点是学习jsp中的一个重要的思想,作为展现层,jsp中不应该出现业务逻辑代码. 当中<%%>代码也会 ...

  2. ES 2015/6 新特性汇总

    ES 2015/6 新特性汇总 箭头函数 箭头函数,通过 => 语法实现的函数简写形式,C#/JAVA8/CoffeeScript 中都有类似语法.与函数不同,箭头函数与其执行下文环境共享同一个 ...

  3. C# 模拟浏览器请求

    public string getHtml(string Url, string type = "UTF-8")        {            try           ...

  4. Python os模块--路径、文件、系统命令等操作

    os模块包含普遍的操作系统功能. 注意:函数参数path是文件或目录的路径,filename是文件的路径,dirname是目录的路径,路径可以是相对路径,也可绝对路径 常见或重要的函数为加粗字体 os ...

  5. Array.apply(null,{length:20})与new Array(20)的区别

    Array.apply(null,{length:20}) 这句代码的实际意义:创建长度为20的一个数组,但并非空数组. 跟new Array(20)的区别在于,前一种创建方式,得到的数组中的每一个元 ...

  6. JAVAEE学习笔记

    以后创建常量有三个名字:Constant   SystemParas   StaticValue 上限或者下限命名      max_    min_ 包含的范围命名     first      l ...

  7. 【LeetCode】332. Reconstruct Itinerary

    题目: Given a list of airline tickets represented by pairs of departure and arrival airports [from, to ...

  8. React 在服务端渲染的实现

    原文地址:Server-Side React Rendering 原文作者:Roger Jin 译者:牧云云 React 在服务端渲染的实现 React是最受欢迎的客户端 JavaScript 框架, ...

  9. Vim按Esc后光标左移问题的解决

    参考了这篇文章http://vim.wikia.com/wiki/Prevent_escape_from_moving_the_cursor_one_character_to_the_left 在Vi ...

  10. less中的变量

     [less中的变量]1.声明变量:@变量名:变量值:使用变量:@变量名:[less中变量的类型]1.数字 数字px2.字符串:无引号字符串 red blue 有引号 "haha" ...