vue+springBoot下载压缩包

前端代码:

//1. 响应下载的输出流
    fileDown(detail.caseId).then(response => {
            const aLink =document.createElement('a')
            const blob = new Blob([response], { type: 'application/zip' })
            let fileName =`${detail.caseId}`
            aLink.href = window.URL.createObjectURL(blob)
            aLink.setAttribute('download', fileName)
            document.body.appendChild(aLink)
            aLink.click()
            document.body.appendChild(aLink)
            }).catch(error => this.$message.error(error))
//下载地址
export function fileDown(caseId) {
  return request({
    url: '/case/zipFileDown/filedown',
    method: 'post',
    params:{caseId:caseId},
    responseType:'blob'
  })
}

后台代码:

package com.ruoyi.lawcase.controller;
import cn.hutool.Hutool;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.lawcase.entity.LawFileEntity;
import com.ruoyi.lawcase.service.LawFileService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("zipFileDown")
public class UrlFilesToZipController{

    private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZipController.class);
    @Resource
    private LawFileService lawFileService;
    @Value("${file.path}")
    private String FILE_ROOT_PATH;


    @PostMapping("filedown")
    public void downTogether(@RequestParam("caseId") String caseId) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 根据caseId 查询出文件URL地址
        QueryWrapper<LawFileEntity> ew = new QueryWrapper<>();
        ew.lambda().eq(LawFileEntity::getFileSendId,caseId);
        List<LawFileEntity> list = lawFileService.list(ew);
        for(int i=0; i<list.size(); i++){
            //从服务器下载文件存储到本地
            downloadFile(list.get(i).getFilePath(),FILE_ROOT_PATH+"/" + caseId,list.get(i).getName());
        }
        try {
            //将下载的文件打成压缩包(ZipUtil工具类,可去官网查看参数的意思)
            ZipUtil.zip(FILE_ROOT_PATH+"/"+caseId,FILE_ROOT_PATH+"/"+caseId+".zip");
            //压缩文件下载,输出给前端
            myDownLoad(FILE_ROOT_PATH,caseId+".zip",response,request);
            //删除下载的临时文件夹
            FileUtil.del(new File(FILE_ROOT_PATH));
        } catch (Exception e) {
            logger.error("打包文件接口异常",e);
        }
    }

    // 从服务器下载文件到本地的方法
    public void downloadFile(String url, String saveAddress,String fileName) {
        //创建不同的文件夹目录
        File file=new File(saveAddress);
        //判断文件夹是否存在
        if (!file.exists())
        {
            //如果文件夹不存在,则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try
        {
            // 建立链接
            URL httpUrl=new URL(url);
            conn=(HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单,默认get方式
            //conn.setRequestMethod("Post");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();
            //获取网络输入流
            inputStream=conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //写入到文件(注意文件保存路径的后面一定要加上文件的名称)
            fileOut = new FileOutputStream(saveAddress + "/" +fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            //保存文件
            while(length != -1)
            {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("抛出异常!!");
        }
    }
    
    // 把压缩文件响应给前端
    public void myDownLoad(String filePath,String fileName, HttpServletResponse response, HttpServletRequest request){
        String filePathF = filePath + "/" + fileName ;
        File f = new File(filePathF);
        if (!f.exists()) {
            try {
                response.sendError(404, "File not found!");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(filePathF));
            byte[] buffer = new byte[fis.available()];
            int index = fis.read(buffer); // 不能删除,否则压缩包解压不开(能正常下载)
            fis.close();
            //清空response
            response.reset();
            //设置response的Header
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Content-disposition", "attachment; filename=" + fileName);
            response.addHeader("Content-Length",""+f.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Vue+SpringBoot批量下载的实现方法: 1.前端Vue代码: ```html <template> <div> <el-button type="primary" @click="downloadAll">批量下载</el-button> </div> </template> <script> export default { methods: { downloadAll() { // 获取需要下载的文件路径列表 const paths = ['path1', 'path2', 'path3']; // 发送POST请求到后端下载接口 this.$axios.post('/downloadAll', paths, { responseType: 'blob' }).then(res => { // 将二进制流转换为文件并下载 const blob = new Blob([res.data], { type: 'application/zip' }); const fileName = 'download.zip'; if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, fileName); } else { const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); window.URL.revokeObjectURL(link.href); } }); } } } </script> ``` 2.后端SpringBoot代码: ```java @RestController @RequestMapping("/download") public class DownloadController { @PostMapping("/downloadAll") public void downloadAll(@RequestBody List<String> paths, HttpServletResponse response) throws IOException { // 创建临时文件夹 File tempDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); tempDir.mkdirs(); // 将需要下载的文件复制到临时文件夹中 for (String path : paths) { File file = new File(path); FileUtils.copyFileToDirectory(file, tempDir); } // 压缩临时文件夹中的文件 File zipFile = new File(System.getProperty("java.io.tmpdir"), "download.zip"); ZipUtil.pack(tempDir, zipFile); // 设置响应头 response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8")); // 将压缩后的文件写入响应流中 try (InputStream in = new FileInputStream(zipFile); OutputStream out = response.getOutputStream()) { IOUtils.copy(in, out); out.flush(); } // 删除临时文件夹和压缩文件 FileUtils.deleteDirectory(tempDir); FileUtils.deleteQuietly(zipFile); } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值