springBoot文件下载 - 从单个文件到多个文件一次性下载

该文章展示了如何在SpringBoot应用中实现单个文件的下载以及多个文件打包成ZIP进行下载。同时,提供了一个工具类来解决文件名在下载过程中的乱码问题。代码示例包括@Controller注解的DownloadController类中的download和zipDownload方法,以及用于处理文件名编码的FileUtils类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、单个文件下载

1、代码

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import com.tyky.common.utils.file.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/dev-api/file")
public class DownloadController {

 @GetMapping("/download")
 public void download (HttpServletRequest request, HttpServletResponse response) throws IOException {

  // 要下载的文件
  Path file = Paths.get("C:\\Users\\ASUS\\Pictures\\壁纸\\素质过硬.jpg");

  // 获取文件的媒体类型
  String contentType = Files.probeContentType(file);
  if (contentType == null) {
   // 如果获取失败,则使用通用的文件类型
   contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
  }

  response.setContentType(contentType);
  // 文件大小
  response.setContentLengthLong(Files.size(file));
  //解决文件乱码
  FileUtils.setAttachmentResponseHeader(response, String.valueOf(file.getFileName()));
  // 响应数据给客户端
  Files.copy(file, response.getOutputStream());
 }
}

2、结果

在这里插入图片描述

二、多个文件下载 - 打包成 ZIP

1、代码

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.tyky.common.utils.file.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/dev-api/file")
public class DownloadController {

    @GetMapping("/downloadToZip")
    public void zipDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 要下载的文件列表
        List<Path> files = Arrays.asList(Paths.get("C:\\Users\\ASUS\\Pictures\\壁纸\\素质过硬.jpg"),
                Paths.get("C:\\Users\\ASUS\\Pictures\\壁纸\\张伟请坐3.jpg"),
                Paths.get("C:\\Users\\ASUS\\Pictures\\壁纸\\张伟专业团队.jpg"));

        // zip压缩
        response.setContentType("application/zip");
        // 解决文件乱码
        FileUtils.setAttachmentResponseHeader(response,"爱情公寓.zip");

        // 压缩多个文件到zip文件中,并且响应给客户端
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            for (Path file : files) {
                try (InputStream inputStream = Files.newInputStream(file)) {
                    zipOutputStream.putNextEntry(new ZipEntry(file.getFileName().toString()));
                    StreamUtils.copy(inputStream, zipOutputStream);
                    zipOutputStream.flush();
                }
            }
        }
    }
}

2、结果

在这里插入图片描述
在这里插入图片描述

三、解决文件名称乱码工具类

public class FileUtils extends org.apache.commons.io.FileUtils
{
    /**
     * 下载文件名重新编码
     *
     * @param response 响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);

        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException
    {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

子笙—望舒

整理编写不易,希望能支持支持

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

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

打赏作者

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

抵扣说明:

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

余额充值