通过JS请求XLSX文件到授权的ASP.NET Web API

时间:2018-08-20 18:11:05

标签: c# jquery ajax asp.net-web-api

我有一个ajax调用我的Web api以获取在调用时生成的xlsx文件。我知道xlsx文件位于正确的内存流中,因为我是直接从服务器下载的,没有任何问题。但是,当我尝试通过浏览器下载文件时,它说该文件无效。我正在使用downloadjs下载数据。

我如何返回流

 public HttpResponseMessage Function_Name() {
        var stream = getStream();

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }

我如何获得信息流

$.ajax({ url: "urlToData", headers: {
                'Authorization': 'Authorization'
            },
         success: function (data) { download(data, "test.xlsx"); } 
});

运行此代码时,我得到一个文件,但是该文件无法在excel中读取。该文件也是15.3 KB,其中直接从服务器下载的功能文件实际上是10.0kb

1 个答案:

答案 0 :(得分:1)

我感到绝望,并尝试了此方法:http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/

当我使用XMLHttpRequest()时,它可以正常工作。

var xhr = new XMLHttpRequest()

xhr.open('GET', 'url', true);
xhr.setRequestHeader('Authorization', 'Authorization');
xhr.responseType = 'blob';

xhr.onload = function(e) {
    if(this.status == 200) {
        var blob = this.response;
        download(this.response, "test.xlsx")
    }
}

xhr.send();