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格式的响应数据,直接用返回值构造下载即可。
问题相关参考截图
- 控制台返回数据:

- 异常文件内容:

内容的提问来源于stack exchange,提问作者Prathamesh Pitale
相关产品推荐
相关产品推荐

