当前位置: 首页 > 编程笔记 >

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

严锐
2023-03-14
本文向大家介绍基于SpringBoot上传任意文件功能的实现,包括了基于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上传任意文件功能的实现就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小牛知识库。

 类似资料:
  • 本文向大家介绍基于Spring实现文件上传功能,包括了基于Spring实现文件上传功能的使用技巧和注意事项,需要的朋友参考一下 本小节你将建立一个可以接受HTTP multi-part 文件的服务。 你将建立一个后台服务来接收文件以及前台页面来上传文件。 要利用servlet容器上传文件,你要注册一个MultipartConfigElement类,以往需要在web.xml 中配置<multipar

  • 本文向大家介绍SpringBoot+layui实现文件上传功能,包括了SpringBoot+layui实现文件上传功能的使用技巧和注意事项,需要的朋友参考一下 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。用我的话来理解

  • 本文向大家介绍springboot+thymeleaf 文件上传功能的实现代码,包括了springboot+thymeleaf 文件上传功能的实现代码的使用技巧和注意事项,需要的朋友参考一下 pom.xml application.yml index.html 文件上传页面 hello.html 上传成功的页面 controller:  文件上传 测试: 注:目前仅实现了文件的上传 计划补充:文件

  • 本文向大家介绍springboot实现文件上传和下载功能,包括了springboot实现文件上传和下载功能的使用技巧和注意事项,需要的朋友参考一下 spring boot 引入”约定大于配置“的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心。大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码。 1.文件上传

  • 本文向大家介绍Golang+Android基于HttpURLConnection实现的文件上传功能示例,包括了Golang+Android基于HttpURLConnection实现的文件上传功能示例的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Golang+Android基于HttpURLConnection实现的文件上传功能。分享给大家供大家参考,具体如下: 这里要演示的是使用Andr

  • 本文向大家介绍SpringBoot实现文件上传下载功能小结,包括了SpringBoot实现文件上传下载功能小结的使用技巧和注意事项,需要的朋友参考一下 最近做的一个项目涉及到文件上传与下载。前端上传采用百度webUploader插件。有关该插件的使用方法还在研究中,日后整理再记录。本文主要介绍SpringBoot后台对文件上传与下载的处理。 单文件上传 如果想要修改文件路径及文件名,修改fileP