使用web Api和angular 2下载大型zip文件

时间:2017-11-09 07:03:16

标签: angular asp.net-core-mvc

获取下载zip文件的Web-API方法

此代码无效

请帮我解决这个问题。

public HttpResponseMessage SampleDownload()
            {
                try {
                    HttpResponseMessage result = null;
                    var path = @"D:\sample\sample.zip";
                    var filename = "sample.zip";
                    if (File.Exists(path))
                    {
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        var stream = new FileStream(path, FileMode.Open);
                        result.Content = new StreamContent(stream);
                        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
                        result.Content.Headers.ContentDisposition.FileName = filename;
                    }
                    return result;
    }

1 个答案:

答案 0 :(得分:1)

C#Web API代码:

public IActionResult GetZipFile(string filename)
{
    // It can be zip file or pdf but we need to change contentType respectively
    const string contentType ="application/zip";
    HttpContext.Response.ContentType = contentType;
    var result = new FileContentResult(System.IO.File.ReadAllBytes(@"{path_to_files}\file.zip"), contentType)
    {
         // It can be zip file or pdf but we need to change the extension respectively
        FileDownloadName = $"{filename}.zip"
    };

    return result;
}

Angular Code:

要求:FileSaver(安装文件保护程序包)

从'file-saver'导入*作为FileSaver;

 this.http.get(url,{ responseType: ResponseContentType.Blob }).subscribe((response)=>{
             var blob = new Blob([response['_body']], {type: "application/zip"});
              FileSaver.saveAs(blob,dlData.file_name);
        }).catch((error) => {
           // Error code
        });

参考网址:How to download a ZipFile from a dotnet core webapi?