如何处理ASP .NET Api HTTPResponseMessage下载文件

时间:2016-12-13 06:28:27

标签: javascript asp.net angularjs ajax asp.net-web-api

我正在阅读如何从asp.net api下载文件的解决方案: https://stackoverflow.com/a/3605510/1881147

因此我创建了一个API处理程序,如下面的代码:

public HttpResponseMessage Post([FromBody]dynamic result)
        {

            var localFilePath = graphDataService.SaveToExcel(graphVm, graphImgUrl);
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
            response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = "testing.xlsx";
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("MS-Excel/xls");

            return response;
            //return graphDataService.SaveToExcel(graphVm, graphImgUrl);
        }

这是我的客户方:

     $http({
            url: '/msexcel',
            method: 'post',
            params: { param: JSON.stringify(param) }
        }).success(function (data, status, headers, config) {
            console.log(data); //HOW DO YOU HANDLE the response here so it downloads?
        }).error(function (data, status, headers, config) {
            console.log(status);
        });

如何处理成功,以便将文件作为.xls文件下载? THX

1 个答案:

答案 0 :(得分:5)

不使用响应内容类型设置为MS-Excel / xls,而是使用application / octet-stream。

public HttpResponseMessage GetFile()
{
    var localFilePath = graphDataService.SaveToExcel(graphVm, graphImgUrl);
    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = "testing.xlsx";
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    response.Content.Headers.Add("x-filename", "testing.xlsx"); //We will use this below
    return response;
}

然后,棘手的部分是如何在成功回调中强制从响应中下载。 一种解决方案是从响应数据中生成blob并再次下载该blob。 在IE中,我们可以保存该blob,但对于大多数浏览器,我们需要欺骗浏览器

$http({
    method: 'GET',
    url: Url,
    responseType: 'arraybuffer',
    headers: {
        'Authorization': Token,
        'Access-Control-Allow-Origin': '*',
    }
}).success(function (data, status, headers) {
    headers = headers();

    var filename = headers['x-filename'];
    var contentType = headers['content-type'];

    try {
        var blob = new Blob([data], { type: contentType });

        //Check if user is using IE
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))
        {
            window.navigator.msSaveBlob(blob, filename);
        }
        else  // If another browser, return 0
        {
            //Create a url to the blob
            var url = window.URL.createObjectURL(blob);
            var linkElement = document.createElement('a');
            linkElement.setAttribute('href', url);
            linkElement.setAttribute("download", filename);

            //Force a download
            var clickEvent = new MouseEvent("click", {
                "view": window,
                "bubbles": true,
                "cancelable": false
            });
            linkElement.dispatchEvent(clickEvent);
        }

    } catch (ex) {
        console.log(ex);
    }
}).error(function (message) {
    console.log(message);
});

注意:*仅在HTML5中支持a-tag上的download属性。 *我通过返回ByteArrayContent来完成这项工作,但StreamContent也应该工作,因为also返回二进制数据。

该解决方案基于this精彩文章,但我在此解决方案中包含对IE的支持