【问题标题】:Saving data(octet-stream) from request as Excel file results in corrupted file将请求中的数据(八位字节流)保存为 Excel 文件会导致文件损坏
【发布时间】:2019-10-14 17:13:14
【问题描述】:

我使用 FileContentResult(byte[], MediaTypeNames.Application.Octet, "file.xlsx" 从 C# API 以八位字节流的形式返回 Excel 文件(工作正常)

然后我想从 js 中打开下载文件提示,一切正常,只是文件已损坏

我一直在尝试这些帖子的各种解决方案,但 Excel 文件总是导致损坏

JavaScript: Create and save file

JavaScript blob filename without link

Create binary blob in JS

还有FileSaver.js

$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: 'application/json',
success: function (result) 
{
    saveFile(result);
}
});

我知道该文件运行良好,因为当我通过 Swagger 对其进行测试时,它运行良好

有什么想法吗?

【问题讨论】:

    标签: javascript c# asp.net-core blob


    【解决方案1】:

    解决方法:

    返回该文件的 base64 并在该页面上创建 a 元素,其 href 属性值为

    data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,

    然后将您的 base64 添加到该值,所以

    'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'+base64

    然后在该链接上执行.click()

    Conversion of Base64 Encoded into XSLX

    您可以使用download=""属性指定文件名

    【讨论】:

      【解决方案2】:

      对我有用的是将 responseType: 'arraybuffer' 添加到 ajax:

      $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        xhrFields: {
          responseType: 'arraybuffer'
        },
        success: function (data) {
          const blob = new Blob([data]);
          saveAs(blob, "output.xlsx");
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2020-07-05
        • 2013-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多