springboot实现批量下载

后端:

java 复制代码
 public void batchDownload(List<User> list, HttpServletResponse response) {
        if (list==null || list.size()<=0) {
            throw new ServiceException("请选择要下载的文件");
        }
        try {
            // 创建临时压缩文件
            String tempFileName = "批量下载_" + System.currentTimeMillis() + ".zip";
            File tempFile = File.createTempFile("temp_", ".zip");

            try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(tempFile))) {
                for (User user : list) {
                    if (user.getKhcl()!=null) {
                        String filePath = basePath + user.getKhcl().getFilePath();
                        File file = new File(filePath);
                        if (file.exists()) {
                            ZipEntry zipEntry = new ZipEntry(user.getKhcl().getFileName());
                            zipOut.putNextEntry(zipEntry);
                            Files.copy(file.toPath(), zipOut);
                            zipOut.closeEntry();
                        }
                    }
                }
            }

            // 设置响应头
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(tempFileName, "UTF-8"));

            // 发送文件
            Files.copy(tempFile.toPath(), response.getOutputStream());

            // 删除临时文件
            tempFile.delete();
        } catch (IOException e) {
            System.out.println(Arrays.toString(e.getStackTrace()));
            throw new ServiceException("批量下载失败:"+e.getMessage());
        }

前端:

javascript 复制代码
export function batchDownload(data) {
  return request({
    url: '/system/user/batchDownload',
    method: 'post',
    data: data,
    responseType: 'blob', // 关键:指定响应类型为blob
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

h5:

javascript 复制代码
            // 使用XMLHttpRequest替代$.ajax,以便正确处理二进制数据
            var xhr = new XMLHttpRequest();
            xhr.open('POST', prefix + '/batchDownload', true);
            xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
            xhr.responseType = 'blob';  // 重要:设置响应类型为blob

            xhr.onload = function() {
                $.modal.closeLoading();

                if (xhr.status === 200) {
                    // 从响应头获取文件名
                    var contentDisposition = xhr.getResponseHeader('Content-Disposition');
                    var filename = "批量下载文件.zip";
                    if (contentDisposition) {
                        var filenameMatch = contentDisposition.match(/filename="?(.+)"?/i);
                        if (filenameMatch && filenameMatch.length > 1) {
                            filename = decodeURIComponent(filenameMatch[1]);
                        }
                    }

                    // 创建Blob对象
                    var blob = new Blob([xhr.response], {type: 'application/zip'});

                    // 创建下载链接
                    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                        // IE浏览器
                        window.navigator.msSaveOrOpenBlob(blob, filename);
                    } else {
                        // 其他浏览器
                        var url = window.URL.createObjectURL(blob);
                        var a = document.createElement('a');
                        a.href = url;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();

                        // 清理
                        setTimeout(function() {
                            document.body.removeChild(a);
                            window.URL.revokeObjectURL(url);
                        }, 100);
                    }

                    $.modal.msgSuccess("下载成功");
                } else {
                    // 尝试解析错误消息
                    var reader = new FileReader();
                    reader.onload = function() {
                        try {
                            var errorResponse = JSON.parse(reader.result);
                            $.modal.alertError("下载失败:" + (errorResponse.msg || errorResponse.message || "未知错误"));
                        } catch (e) {
                            $.modal.alertError("下载失败,状态码:" + xhr.status);
                        }
                    };
                    reader.readAsText(xhr.response);
                }
            };

            xhr.onerror = function() {
                $.modal.closeLoading();
                $.modal.alertError("下载请求失败,请检查网络连接");
            };

            xhr.send(JSON.stringify(list));
相关推荐
神奇的程序员16 小时前
从已损坏的备份中拯救数据
运维·后端·前端工程化
oden16 小时前
AI服务商切换太麻烦?一个AI Gateway搞定监控、缓存和故障转移(成本降40%)
后端·openai·api
ะัี潪ิื16 小时前
springboot加载本地application.yml和加载Consul中的application.yml配置反序列化LocalDate类型差异
spring boot·consul·java-consul
李慕婉学姐17 小时前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
m0_7400437317 小时前
SpringBoot05-配置文件-热加载/日志框架slf4j/接口文档工具Swagger/Knife4j
java·spring boot·后端·log4j
zdd5678918 小时前
关于Windows 11 家庭中文版 25H2中ensp无法启动路由器,报40错的解决方法
windows
招风的黑耳18 小时前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
大佐不会说日语~18 小时前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
Miss_Chenzr18 小时前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
程序员游老板18 小时前
基于SpringBoot3+vue3的爱心陪诊平台
java·spring boot·毕业设计·软件工程·课程设计·信息与通信