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

发布时间 2023-09-10 18:45:41作者: Xproer-松鼠

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

 

文件上传

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

 

依赖

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

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-web</artifactId>

</dependency>

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

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

配置

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

 

# 文件上传的最大值

spring.servlet.multipart.max-file-size=10MB

# 文件请求的最大值

spring.servlet.multipart.max-request-size=10MB

# 临时文件存储路径

spring.servlet.multipart.location=/tmp

 

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";

    }

}

 

在上面的代码中,我们定义了一个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 Upload</title>

</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">Upload</button>

    </form>

</body>

</html>

 

在上面的代码中,我们使用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>

 

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

 

运行

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

 

总结

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

 

 

参考文章:http://blog.ncmem.com/wordpress/2023/09/10/springboot-%e5%a6%82%e4%bd%95%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e5%92%8c%e4%b8%8b%e8%bd%bd/

欢迎入群一起讨论