基于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默认传入时间段时间的实例

    Java默认传入时间段时间的实例

    下面小编就为大家带来一篇Java默认传入时间段时间的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • jvm排查工具箱jvm-tools下载使用详解

    jvm排查工具箱jvm-tools下载使用详解

    这篇文章主要为大家介绍了jvm排查工具箱jvm-tools下载使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • Java遍历Map对象集合的六种方式代码示例

    Java遍历Map对象集合的六种方式代码示例

    Java中的Map是一种键值对映射的数据结构,它提供了一些常用的方法用于获取、添加、删除和修改元素,下面这篇文章主要给大家介绍了关于Java遍历Map对象集合的六种方式,需要的朋友可以参考下
    2024-02-02
  • 浅谈Spring Cloud zuul http请求转发原理

    浅谈Spring Cloud zuul http请求转发原理

    这篇文章主要介绍了浅谈Spring Cloud zuul http请求转发原理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08
  • 关于Java中String类字符串的解析

    关于Java中String类字符串的解析

    这篇文章主要介绍有关Java中String类字符串的解析,在java中,和C语言一样,也有关于字符串的定义,并且有他自己特有的功能,下面就进入主题一起学习下面文章内容吧
    2021-10-10
  • Mybatis基于xml配置实现单表的增删改查功能

    Mybatis基于xml配置实现单表的增删改查功能

    这篇文章主要介绍了Mybatis基于xml配置实现单表的增删改查,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-04-04
  • java 使用异常的好处总结

    java 使用异常的好处总结

    这篇文章主要介绍了java 使用异常的好处总结的相关资料,需要的朋友可以参考下
    2017-03-03
  • 浅谈JackSon的几种用法

    浅谈JackSon的几种用法

    这篇文章主要介绍了浅谈JackSon的几种用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Netty分布式pipeline管道传播outBound事件源码解析

    Netty分布式pipeline管道传播outBound事件源码解析

    这篇文章主要介绍了Netty分布式pipeline管道传播outBound事件源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-03-03
  • Spring Boot 集成Elasticsearch模块实现简单查询功能

    Spring Boot 集成Elasticsearch模块实现简单查询功能

    本文讲解了Spring Boot集成Elasticsearch采用的是ES模板的方式实现基础查询,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2022-06-06

最新评论