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

在前面的文章中,我们介绍了如何在Spring Boot中实现单个文件的上传和下载。但是,有时候我们需要实现多个文件的上传和批量下载,本文将介绍如何在Spring Boot中实现多文件上传和批量下载的功能。

在这里插入图片描述

多文件上传

在Spring Boot中,实现多文件上传与单文件上传类似,主要区别在于前端表单中需要使用多个文件输入框,并且在后端Controller中需要使用MultipartFile数组来接收多个文件。下面是一个示例代码:

Controller

@Controller
public class MultipleFileUploadController {
    @PostMapping("/multiple-upload")
    public String multipleUpload(@RequestParam("file") MultipartFile[] files, RedirectAttributes redirectAttributes) {

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
                return "redirect:multiple-upload";
            }
            try {
                // 保存文件
                byte[] bytes = file.getBytes();
                Path path = Paths.get("/tmp/" + file.getOriginalFilename());
                Files.write(path, bytes);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        redirectAttributes.addFlashAttribute("message", "You successfullyuploaded " + files.length + " files");
        return "redirect:multiple-upload";
    }
}

在上面的代码中,我们使用@RequestParam注解来接收前端传递过来的MultipartFile数组。然后,我们遍历数组中的每个文件,检查其是否为空。如果文件为空,我们将返回上传表单页面,并显示错误消息。如果文件上传成功,我们将重定向到上传表单页面,并显示成功消息。

模板

为了实现多文件上传,我们需要在前端表单中使用多个文件输入框。下面是一个使用Thymeleaf的HTML文件示例:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Multiple 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="@{/multiple-upload}">
        <div class="form-group">
            <label for="file">Select files to upload:</label>
            <input type="file" id="file" name="file" multiple>
        </div>
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>
</body>
</html>

在上面的代码中,我们使用Thymeleaf的multiple属性指定文件输入框可以选择多个文件。

批量下载

在Spring Boot中实现批量下载,我们可以使用ZipOutputStream将多个文件打包成一个压缩文件,然后将该压缩文件发送给浏览器。下面是一个示例代码:

Controller

@Controller
public class BatchFileDownloadController {
    @GetMapping("/batch-download")
    public void batchDownload(HttpServletResponse response) throws IOException {

        // 获取要下载的文件列表
        List<File> files = new ArrayList<>();
        files.add(new File("/tmp/file1.txt"));
        files.add(new File("/tmp/file2.txt"));
        files.add(new File("/tmp/file3.txt"));

        // 设置响应头信息
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=batch-download.zip");

        // 创建ZipOutputStream
        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

        // 将文件添加到压缩包中
        for (File file : files) {
            zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
            FileInputStream fileInputStream = new FileInputStream(file);
            IOUtils.copy(fileInputStream, zipOutputStream);
            fileInputStream.close();
            zipOutputStream.closeEntry            ();
        }

        // 关闭ZipOutputStream
        zipOutputStream.close();
    }
}

在上面的代码中,我们首先获取要下载的文件列表,然后设置响应头信息,创建ZipOutputStream并将文件添加到压缩包中。最后,我们关闭ZipOutputStream并将压缩文件发送给浏览器。

模板

为了实现批量下载,我们可以在前端页面中添加一个链接或按钮,该链接或按钮将触发文件批量下载。下面是一个使用Thymeleaf的HTML文件示例:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Batch File Download</title>
</head>
<body>
    <a th:href="@{/batch-download}" class="btn btn-primary">Download Files</a>
</body>
</html>

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

总结

在本文中,我们介绍了如何在Spring Boot中实现多文件上传和批量下载的功能。在实现多文件上传时,我们需要使用MultipartFile数组来接收多个文件,并在前端表单中使用多个文件输入框。在实现批量下载时,我们可以使用ZipOutputStream将多个文件打包成一个压缩文件,并将该压缩文件发送给浏览器。Spring Boot提供了简单且易于使用的方式来实现多文件上传和批量下载,这对于许多Web应用程序来说是非常重要的功能。在实现多文件上传和批量下载时,需要注意安全性和文件大小的限制,并根据实际需求进行相应的配置。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT徐师兄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值