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));
相关推荐
乐橙开放平台7 分钟前
一周上线校园透明化:listDeviceDetailsByPage 台账 + getKitToken + ImouPlayer 多路墙
后端·物联网·安全·音视频·智能家居
樊小肆15 分钟前
# 你还在等DeepSeek官方 agent Harness‌? 来试试 DeepSeeker-Code吧
前端·人工智能·后端
樊小肆15 分钟前
2568 万 token 才花 2 块 2:聊聊 DeepSeeker-Code 怎么吃满上下文缓存
前端·人工智能·后端
众人皆醒我独醉15 分钟前
大模型训练优化:FSDP、DeepSpeed ZeRO 与混合精度
后端·面试·gpu
Zane199428 分钟前
ClassName() 只是一步?拆开看 __new__ 和 __init__ 各自在干什么
后端·python
geovindu29 分钟前
java: Memento Pattern
java·开发语言·后端·备忘录模式·行为模式
星哥的编程之路32 分钟前
万字深度解析 Agent 学习路线
后端
程序边界35 分钟前
SQL Server数据迁移这件事,远比你想的复杂——但也远比你想的简单(下)
后端
Zane199437 分钟前
JRE 去哪了?一次讲清楚 JDK、JRE、JVM 到底是什么关系?
java·后端
用户31268748772041 分钟前
你的配置真的绑定上了吗?Spring Boot @ConfigurationProperties 全链路拆解
spring boot