Download base64 data as a file in ASP.NET MVC

How to download base64 data as file in ASP.NET MVC

Sometimes we have to use base64 data and download that data as a file.

What is base64 ?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation (form Wikipedia). 

what is base64

In this article we are discussing how to download base64 data as a file in ASP.NET MVC. Here we are downloading a csv file which created from base64 data. Please refer this article if you want to learn how to implement file download function in ASP.NET MVC. This is only a one way to achieve this task and I hope to explain other methods also in a new article.

First add the controller action method to read the base64 data, create the file and download.

Controller Action
[HttpGet]
public virtual void DownloadCSV()
{

var file = GetBase64Data();

if (file != null)
{
string base64data = string.Empty;
string fileName = DateTime.Now.ToString() + "_MyData.csv";

base64data = file;

byte[] bytes = Convert.FromBase64String(base64data);

var response = new FileContentResult(bytes, "text/csv");
response.FileDownloadName = fileName;

Response.Clear();
Response.AddHeader("content-disposition", "inline; filename=" + fileName);
Response.ContentType = "text/csv";
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.End();
}

}
}

// This method returns sample base64 data 
public string GetBase64Data()
{

return "Q3VzdG9tZXIgYWNjb3VudCxDdXN0b21lciBuYW1lLEl0ZW0gbnVtYmVyLEl0ZW0gbmFtZSxT
YWxlcyBvcmRlcixPcmRlcmVkIHF1YW50aXR5LERlbGl2ZXJlZCBxdWFudGl0eSxRdWFudGl0
eSByZW1haW5pbmcsT3JkZXIgZGF0ZQ=="

}

In the view we can put a link to download the data and call the controller method using Ajax

<div>
<a class="download-csv"  target="_blank">Download CSV</a>
</div>
Script
var url ="Controller/DownloadCSV";

$.ajax(
{
url: url,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
type: "GET",
success: function () {

window.location = url;
}
});

 

This will download the created csv file from the base64 data.  You can use this site for encoding and decoding base64 data to test this app.

Sajith Dilhan on FacebookSajith Dilhan on Linkedin
Sajith Dilhan
Software Developer at Sana Commerce

Leave a Reply

Your email address will not be published. Required fields are marked *