Ryn901
Ryn901

Reputation: 183

Blazor Server create link to download file from byte array

I have a method in my code behind to retrieve a get a pdf file from an API and return the byte[]

byte[] byteArray = response.Content.ReadAsByteArrayAsync().Result; ;
        using (MemoryStream pdfStream = new MemoryStream())
        {           
            pdfStream.Write(byteArray, 0, byteArray.Length);
            pdfStream.Position = 0;
            return new FileStreamResult(pdfStream, "application/pdf");
        }

How in Blazor server to I create a link in my .razor component to consume this byte[] so that when the user clicks the link, it triggers the file download?

Upvotes: 3

Views: 5378

Answers (1)

Whit Waldo
Whit Waldo

Reputation: 5217

Your solution is close because you're creating the appropriate result, but you simply need the method that returns it.

Set up your API controller like the following:

[ApiController]
public class DownloadController : ControllerBase {
  [HttpGet]
  public ActionResult Get() {
  byte[] byteArray = response.Content.ReadAsByteArrayAsync().Result; ;
      using (MemoryStream pdfStream = new())
      {           
          pdfStream.Write(byteArray, 0, byteArray.Length);
          pdfStream.Position = 0;
          var result = FileStreamResult(pdfStream, "application/pdf");
          result.FileDownloadName = "sample.txt";
          return result;
      }
  }
}

Upvotes: 1

Related Questions