Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
Ryn901 Avatar asked Dec 06 '25 07:12

Ryn901


1 Answers

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;
      }
  }
}
like image 81
Whit Waldo Avatar answered Dec 12 '25 10:12

Whit Waldo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!