使用httpresponsemessage下载文件

时间:2019-04-26 14:20:16

标签: javascript asp.net backbone.js

我有一个ASP.Net Web API应用程序,该应用程序通过HttpResponseMessage响应请求,但是在javascript客户端上接收该请求时遇到了问题。

该zip文件将打开并在服务器上正确提取,并且会在客户端上下载。但是,当我尝试打开文件时,出现无效错误的压缩zip文件夹。是否因为我从客户端下载文件的方式错误?我正在使用ASP.Net 5,客户端是Chrome。

Javascript:

    static downloadFile(data) {
        var filename = 'parentreport.zip';
        console.log(typeof data);
        var blob = new Blob([data], {
            type: 'application/octet-stream' });
        //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);
        linkElement.click();
            //Force a download
            var clickEvent = new MouseEvent("click", {
                "view": window,
                "bubbles": true,
                "cancelable": false
            });
            linkElement.dispatchEvent(clickEvent);
        }
    }

ASP.NET API:

public async Task<IHttpActionResult> GetReport()
{
    string localFilePath = 
    System.Web.HttpContext.Current.Server.MapPath($"~/App_Data/5ce962c6-5db5-4b0a-90bf-c54a53381d7d.zip");//zip file previously created using System.IO.Compression.Zipfile via another process
    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 = localFilePath;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    return ResponseMessage(response);

}    

我希望文件能够成功传输,并能够打开zip文件。

0 个答案:

没有答案