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

jay*_*jay 2 javascript asp.net ajax asp.net-web-api angularjs

我在这里阅读如何从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);
        }
Run Code Online (Sandbox Code Playgroud)

这是我的客户端:

     $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);
        });
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*und 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;
}
Run Code Online (Sandbox Code Playgroud)

然后,棘手的部分是如何在成功回调中强制从响应中进行下载。一种解决方案是从响应数据中创建一个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);
});
Run Code Online (Sandbox Code Playgroud)

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

该解决方案基于这篇出色的文章,但我在此解决方案中包括了对IE的支持