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

 更新时间:2017年08月01日 20:17:21   投稿:jingxian  
下面小编就为大家带来一篇基于SpringBoot上传任意文件功能的实现。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

三、实现的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

五、服务启动时的处理

六、测试成功的结果

以上这篇基于SpringBoot上传任意文件功能的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java Stream实现多字段分组groupingBy操作详解

    Java Stream实现多字段分组groupingBy操作详解

    Stream是Java8的一个新特性,主要用户集合数据的处理,如排序、过滤、去重等等功能,本文就来讲讲如何利用Stream实现比较优雅的按多字段进行分组groupingBy吧
    2023-06-06
  • MyEclipse安装JS代码提示的教程(Spket插件)

    MyEclipse安装JS代码提示的教程(Spket插件)

    本篇文章主要介绍了MyEclipse安装JS代码提示的教程(Spket插件),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • Java拼接字符串时如何去掉最后一个多余的逗号

    Java拼接字符串时如何去掉最后一个多余的逗号

    当我们遍历拼接字符串的时候,最后会多出一个我们添加的字符(比如逗号),下面通过实例代码给大家介绍Java拼接字符串时去掉最后一个多余的逗号,感兴趣的朋友跟随小编一起看看吧
    2024-12-12
  • 基于Spring Boot的线程池监控问题及解决方案

    基于Spring Boot的线程池监控问题及解决方案

    这篇文章主要介绍了基于Spring Boot的线程池监控方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • 详解Servlet3.0新特性(从注解配置到websocket编程)

    详解Servlet3.0新特性(从注解配置到websocket编程)

    Servlet3.0的出现是servlet史上最大的变革,其中的许多新特性大大的简化了web应用的开发,为广大劳苦的程序员减轻了压力,提高了web开发的效率。
    2017-04-04
  • Java中的collection集合类型总结

    Java中的collection集合类型总结

    Java的集合类型都是对java.util包中Collection接口的继承,这里我们主要介绍依赖于collection的一些主分支,一起来看一下Java中的collection集合类型总结
    2016-05-05
  • Java黑科技:replace首个替换一秒搞定

    Java黑科技:replace首个替换一秒搞定

    要实现只替换第一个匹配项,可以使用Java中的String类的replaceFirst方法,该方法接受两个参数,第一个参数是要替换的字符串或正则表达式,第二个参数是替换后的字符串,需要的朋友可以参考下
    2023-10-10
  • Java 正则表达式功能及应用

    Java 正则表达式功能及应用

    自从jdk1.4推出java.util.regex包,就为我们提供了很好的Java正则表达式应用平台,因为Java正则表达式是一个很庞杂的体系。
    2010-03-03
  • idea插件生成jpa实体类的实现示例

    idea插件生成jpa实体类的实现示例

    本文主要介绍了idea插件生成jpa实体类的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-01-01
  • 详解JDK 5 Annotation 注解之@Target的用法介绍

    详解JDK 5 Annotation 注解之@Target的用法介绍

    这篇文章主要介绍了详解JDK 5 Annotation 注解之@Target的用法介绍,需要的朋友可以参考下
    2016-02-02

最新评论