基于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上传任意文件功能的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 一文详解SpringBoot如何优雅地实现异步调用

    一文详解SpringBoot如何优雅地实现异步调用

    SpringBoot想必大家都用过,但是大家平时使用发布的接口大都是同步的,那么你知道如何优雅的实现异步呢?这篇文章就来和大家详细聊聊
    2023-03-03
  • Java实现快速生成词云图的示例代码

    Java实现快速生成词云图的示例代码

    词云(Word Cloud),又称文字云、标签云(Tag Cloud)、关键词云(Keyword Cloud),是对文本信息中一定数量的关键词出现的频率高低情况的一种可视化展现方式。本文将用Java代码实现快速生成词云图,需要的可以参考一下
    2023-02-02
  • Java maven三种仓库,本地仓库,私服,中央仓库的配置

    Java maven三种仓库,本地仓库,私服,中央仓库的配置

    今天给大家简单介绍Maven三种仓库的配置,文中有非常详细的解释,对Java初学者很有帮助哟,需要的朋友可以参考下,希望能够给你带来帮助
    2021-09-09
  • java8 stream自定义分组求和并排序的实现

    java8 stream自定义分组求和并排序的实现

    这篇文章主要介绍了java8 stream自定义分组求和并排序的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • 在SpringBoot中整合数据源的示例详解

    在SpringBoot中整合数据源的示例详解

    这篇文章主要介绍了在SpringBoot中如何整合数据源,本文介绍了如何在SpringBoot项目中整合常见的数据源,包括JdbcTemplate、MyBatis和JPA,并探讨了如何配置和使用多数据源,需要的朋友可以参考下
    2023-06-06
  • SpringBoot大学心理服务系统实现流程分步讲解

    SpringBoot大学心理服务系统实现流程分步讲解

    本系统主要论述了如何使用JAVA语言开发一个大学生心理服务系统 ,本系统将严格按照软件开发流程进行各个阶段的工作,采用B/S架构,面向对象编程思想进行项目开发
    2022-09-09
  • Java Socket实现简易聊天室

    Java Socket实现简易聊天室

    这篇文章主要为大家详细介绍了Java Socket实现简易聊天室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-03-03
  • Spring boot easyexcel 实现复合数据导出、按模块导出功能

    Spring boot easyexcel 实现复合数据导出、按模块导出功能

    这篇文章主要介绍了Spring boot easyexcel 实现复合数据导出、按模块导出,实现思路流程是准备一个导出基础填充模板,默认填充key,本文给大家介绍的非常详细,需要的朋友可以参考下
    2023-09-09
  • springboot ConfigurationProperties的绑定源码示例解析

    springboot ConfigurationProperties的绑定源码示例解析

    这篇文章主要为大家介绍了springboot ConfigurationProperties的绑定源码示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • Java日常练习题,每天进步一点点(13)

    Java日常练习题,每天进步一点点(13)

    下面小编就为大家带来一篇Java基础的几道练习题(分享)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望可以帮到你
    2021-07-07

最新评论