【问题标题】:Requesting XLSX file through js to authorized asp.net web api通过js向授权的asp.net web api请求XLSX文件
【发布时间】:2019-01-26 21:57:14
【问题描述】:

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

我如何返回 Stream

 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

【问题讨论】:

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


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-18
      • 2015-03-03
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 1970-01-01
      相关资源
      最近更新 更多