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

ASP.NET Core Ajax下载生成文件仅显示[object Object]如何解决

问题根因

接口返回的data是JavaScript对象类型,直接传入Blob构造函数时,对象会被隐式转换为字符串,转换结果固定为[object Object],这就是下载文件内容错误的直接原因。Blob不会自动将对象序列化为JSON格式字符串。

修复方法

对返回的对象做显式JSON序列化后再传入Blob即可,额外补充了内存释放的优化逻辑,修正后代码如下:

$.ajax({
    type: "POST",
    url: vGenerateUrl,
    data: { IDs: ids, SupplyType:supplyType, SubType:subType, DocType:docType, TransMode:transMode },
    success: function(data) {
        console.log(data);
        DevExpress.ui.notify({ message: "xyz Generated", width: 1300 }, vSuccessMsgType, 3000);
        // 序列化对象为格式化的JSON字符串,不需要缩进可读可以去掉null,2参数
        const fileContent = JSON.stringify(data, null, 2);
        const blob = new Blob([fileContent], { type: 'application/json' });
        const a = document.createElement('a');
        const fileUrl = window.URL.createObjectURL(blob);
        a.href = fileUrl;
        a.download = 'a.json';
        document.body.appendChild(a);
        a.click();
        // 清理临时DOM和内存占用
        document.body.removeChild(a);
        window.URL.revokeObjectURL(fileUrl);
    },
    error: function(result) {
        onAjaxError(result);
    }
});

额外场景说明

如果你后续要下载PDF、Excel等二进制格式文件,不需要做JSON序列化,只需要给Ajax请求新增配置xhrFields: { responseType: 'blob' },让jQuery直接返回Blob格式的响应数据,直接用返回值构造下载即可。

问题相关参考截图

  • 控制台返回数据:控制台打印的文件数据
  • 异常文件内容:下载得到的Json文件内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:12:26