Exporting Files From .NET To JavaScript Apps

In this article, we will analyze how to export files from .NET to a Javascript app (like React.js), This means returning a file using an endpoint and downloading the file from the client side. 

First, let's see the code in .NET we have a controller with this endpoint to return the file:

[HttpGet("export/{fileName}")]
[ProducesResponseType(typeof(FileContentResult), 200)]
public async Task<IActionResult> Export(string fileName)
{
     // file from folder you can get the bytes from Azure blob storage, Amazon S3, etc...
     byte[] FileInBytes = System.IO.File.ReadAllBytes(@"C:\WriteText.txt");

     return File(FileInBytes , "text/plain", fileName);
}

fileName is an optional parameter that includes the name of the file. You can also create a 

We are returning a FileContentResult, We can also return the array of bytes, but for this scenario, FileContentResult is a better approach and easier to implement in the frontend.

It doesn't matter if your file comes from Azure Blob storage, Amazon S3, or local sources at the end you need to read the bytes and return a FileContentResult. 

With this implementation now, we only need to call the endpoint path using href property in JavaScript.

export async function getExportFile() {

  window.location.href = `${API_URL}/api/MyEndpoint/export/FileName`;

}

You only need to replace API_URL with the URL of your API and then your endpoint. The browser will be in charge of downloading the file. 


Similar Articles