首页 > 解决方案 > C# .net core WEB-API "proxy" file download

问题描述

I have an angular frontend (with a pdf viewer) and a C# .net core API.

The .net core API is downloading a file (from an internal API) and then serves this file to the angular pdf viewer (like a proxy). It works fine but the load time is quite long as the backend downloads the whole file and then serves it to the frontend. Is there a way to retrieve the file in the api and at the same time deliver those pieces to the frontend?

So read the file in chunks to the memory stream and at the same time serve it to the frontend?

Currenty implementation:

WebClient webClient = new WebClient();
webClient.Headers.Add("Authorization", "Basic xxxxx");
var file = webClient.DownloadData("http://xxxx/" + id + "/pdf");
Stream stream = new MemoryStream(file);
return new FileStreamResult(stream, "application/pdf");

标签: c#angular.net-coreasp.net-core-webapi

解决方案


Your issue is that DownloadData doesn't continue until it's downloaded the whole file. Try this to stream the data through instead

WebClient webClient = new WebClient();
webClient.Headers.Add("Authorization", "Basic xxxxx");
var stream = webClient.OpenRead("http://xxxx/" + id + "/pdf");
return new FileStreamResult(stream, "application/pdf");

推荐阅读