You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js Excel文件下载功能异常:下载文件损坏排查求助

解决下载Excel文件损坏的问题

核心原因是你的请求没有正确处理二进制响应,浏览器默认会把二进制数据解析为字符串,导致生成Blob时文件损坏;而Postman会自动识别并处理二进制响应,所以能正常打开。

解决方案

1. 修改请求配置,指定响应类型为二进制

在getDiscussionExport方法的__request配置中添加responseType,确保返回原始二进制数据:

public static async getDiscussionExport({
key,
afterId,
hideCsrData = true,
exportType = 'Word',
}: {
key: string,
afterId?: number,
hidexyzData?: boolean,
exportType?: 'Word' | 'Excel',
}): Promise<Blob | ArrayBuffer> {
        const result = await __request({
            method: 'GET',
            path: `xxxx`,
            query: {
                'afterId': afterId,
                'hidexyzData': hidexyzData,
                'exportType': exportType,
            },
            errors: {
                403: `Error: Forbidden`,
                422: `Error: Unprocessable Entity`,
            },
            // 新增:指定响应类型为blob(或arraybuffer)
            responseType: 'blob'
        });
        return result.body;
    }

2. 调整下载逻辑

如果请求返回的是Blob类型,直接使用即可,无需再次包装:

async downloadExcel() {
    try {
        const blob = await InteractionService.getDiscussionExport({key: '5', exportType: 'Excel'});

        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'csr-discussion.xlsx');
        document.body.appendChild(link);
        link.click();

        // 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
    } catch (error) {
        console.error('Error downloading Excel file:', error);
    }
}

如果你的__request工具不支持responseType: 'blob',可以改用responseType: 'arraybuffer',然后在下载逻辑中将ArrayBuffer转为Blob:

// 请求配置改为
responseType: 'arraybuffer'

// 下载逻辑调整
const arrayBuffer = await InteractionService.getDiscussionExport({key: '5', exportType: 'Excel'});
const blob = new Blob([arrayBuffer], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});

额外检查

确认后端返回的响应头Content-Type是否为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,这能帮助浏览器正确识别文件类型。

内容的提问来源于stack exchange,提问作者Demogeek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:20:16