• SpringBoot 如何实现文件上传和下载


    当今Web应用程序通常需要支持文件上传和下载功能,Spring Boot提供了简单且易于使用的方式来实现这些功能。在本篇文章中,我们将介绍Spring Boot如何实现文件上传和下载,同时提供相应的代码示例。

    在这里插入图片描述

    文件上传

    Spring Boot提供了Multipart文件上传的支持。Multipart是HTTP协议中的一种方式,用于支持文件上传。下面我们将介绍如何在Spring Boot中实现文件上传。

    依赖

    在开始之前,我们需要在pom.xml文件中添加以下依赖:

    <dependency>
       <groupId>org.springframework.bootgroupId>
       <artifactId>spring-boot-starter-webartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    此外,如果您希望使用Thymeleaf进行模板渲染,可以添加以下依赖:

    <dependency>
       <groupId>org.springframework.bootgroupId>
       <artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
    
    • 1
    • 2
    • 3
    • 4

    配置

    在application.properties文件中添加以下配置:

    # 文件上传的最大值
    spring.servlet.multipart.max-file-size=10MB
    # 文件请求的最大值
    spring.servlet.multipart.max-request-size=10MB
    # 临时文件存储路径
    spring.servlet.multipart.location=/tmp
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    Controller

    在Spring Boot中实现文件上传需要编写一个Controller,其中包含两个方法,一个用于返回上传文件的表单页面,另一个用于实际处理文件上传。

    @Controller
    public class FileUploadController {
    
        @GetMapping("/upload")
        public String uploadForm(Model model) {
            return "upload";
        }
    
        @PostMapping("/upload")
        public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
            if (file.isEmpty()) {
                redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
                return "redirect:upload";
            }
    
            try {
                // 保存文件
                byte[] bytes = file.getBytes();
                Path path = Paths.get("/tmp/" + file.getOriginalFilename());
                Files.write(path, bytes);
    
                redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            return "redirect:upload";
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    在上面的代码中,我们定义了一个GET请求处理方法uploadForm,它返回一个上传文件的表单页面。在POST请求处理方法uploadFile中,我们使用@RequestParam注解获取上传的文件,然后将其保存到指定的路径中。如果文件为空,我们将重定向到上传表单页面,并显示错误消息。如果文件上传成功,我们将重定向到上传表单页面,并显示成功消息。

    模板

    为了使上传表单页面显示在浏览器中,我们需要创建一个Thymeleaf模板文件upload.html,其中包含上传表单页面的HTML代码。

    DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>File Uploadtitle>
    head>
    <body>
        <div th:if="${message}" class="alert alert-success" th:text="${message}">div>
        <form method="post" enctype="multipart/form-data" th:action="@{/upload}">
            <div class="form-group">
                <label for="file">Select a file to upload:label>
                <input type="file" id="file" name="file">
            div>
            <button type="submit" class="btn btn-primary">Uploadbutton>
        form>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在上面的代码中,我们使用Thymeleaf的if语句和text属性显示上传成功或失败的消息。我们还使用Thymeleaf的action属性指定表单提交的URL,enctype属性设置表单的编码类型为multipart/form-data,这是文件上传时必须使用的编码类型。

    运行

    现在我们已经完成了文件上传的代码和模板,我们可以运行Spring Boot应用程序,并在浏览器中访问/upload路径,即可看到上传表单页面。选择要上传的文件并点击“上传”按钮,文件将被保存到指定的路径中。

    文件下载

    Spring Boot提供了简单的方式来实现文件下载。下面我们将介绍如何在Spring Boot中实现文件下载。

    Controller

    与文件上传类似,我们需要编写一个Controller来处理文件下载请求。在Controller中,我们可以使用ResponseEntity来将文件内容发送到浏览器。

    @Controller
    public class FileDownloadController {
    
        @GetMapping("/download")
        public ResponseEntity<Resource> downloadFile() throws IOException {
            Path path = Paths.get("/tmp/file.txt");
            Resource resource = new InputStreamResource(Files.newInputStream(path));
    
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt");
    
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(Files.size(path))
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource### 模板
    
    为了使文件下载工作,我们需要在浏览器中添加一个链接或按钮,该链接或按钮将触发文件下载。我们可以将该链接或按钮包含在一个HTML文件中。下面是一个使用Thymeleaf的HTML文件示例:
    
    ```html
    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>File Download</title>
    </head>
    <body>
        <a th:href="@{/download}" class="btn btn-primary">Download File</a>
    </body>
    </html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在上面的代码中,我们使用Thymeleaf的href属性指定文件下载的URL,这里指向/download。

    运行

    现在我们已经完成了文件下载的代码和模板,我们可以运行Spring Boot应用程序,并在浏览器中访问/download路径,即可开始文件下载。点击链接或按钮,浏览器将下载文件并将其保存到本地磁盘中。

    总结

    在本文中,我们介绍了Spring Boot如何实现文件上传和下载,包括依赖、配置、Controller和模板的编写。通过本文,您应该能够了解文件上传和下载在Spring Boot中的实现方式,并可以使用相应的代码示例进行实践。Spring Boot提供了简单且易于使用的方式来实现文件上传和下载,这对于许多Web应用程序来说是非常重要的功能。在实现文件上传和下载时,需要注意安全性和文件大小的限制,并根据实际需求进行相应的配置。

  • 相关阅读:
    numpy傅里叶变换
    概要设计:描绘软件结构的图形工具,结构图既能表示模块间的数据信息、控制信息,也能表示选择调用和循环调用关系。
    AUTOSAR之CanNm全局配置概述
    学习c#的第二十一天
    SpringBoot 根据不同环境切换不同文件路径
    MSP430嵌入式接口编程(惯性测量单元温湿度双音多频磁力计LCD显示等)
    如何通过C++ 将数据写入 Excel 工作表
    【脚本】 【Linux】循环执行命令
    1.驱动的认知
    Ansys Optics Launcher 提升客户体验
  • 原文地址:https://blog.csdn.net/yujun2023/article/details/130905253