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

一、单个文件下载

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");
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现多文件上传的方式有很多种,下面我将介绍一种基于 Vue 和 Spring Boot 的实现方式,使用的是 Element UI 的上传组件 el-upload。 前端实现: 1. 在 Vue 组件中引入 Element UI 的 el-upload 组件。 ```vue <template> <el-upload class="upload-demo" action="/api/upload" :multiple="true" :on-change="handleUploadChange" :on-remove="handleUploadRemove" :file-list="fileList"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> ``` 2. 在 Vue 组件中定义 fileList 数组,用于存储上传的文件列表。 ```vue <script> export default { data() { return { fileList: [] } }, methods: { handleUploadChange(file, fileList) { this.fileList = fileList }, handleUploadRemove(file, fileList) { this.fileList = fileList } } } </script> ``` 3. 在 Vue 组件中定义 handleUploadChange 和 handleUploadRemove 方法,用于监听上传文件的变化和删除文件的操作,更新 fileList 数组。 后端实现: 1. 在 Spring Boot 项目中定义上传文件的接口。 ```java @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile[] files) { // TODO: 处理上传的文件 return ResponseEntity.ok("上传成功"); } } ``` 2. 在接口中使用 @RequestParam 注解接收上传的文件,可以使用 MultipartFile 类型的数组来接收多个文件。接收到文件后,可以根据需要进行处理,例如保存到本地磁盘或上传到云存储服务。 3. 在 application.properties 文件中配置文件上传的相关参数。 ```properties # 文件上传配置 spring.servlet.multipart.max-file-size=500KB spring.servlet.multipart.max-request-size=100MB spring.servlet.multipart.enabled=true ``` 其中,max-file-size 和 max-request-size 分别设置了单个文件和总文件大小的最大值,enabled 表示是否启用文件上传功能。 以上就是基于 Vue 和 Spring Boot 的多文件上传实现方式,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值