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. If you have come across this as a challenge, then you can follow this article to get rid of your headache.
So 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 (from Wikipedia).
This is the definition from Wikipedia.
In this article we are discussing how to download base64 data 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. And also here we are discussing only the basics of this method.
We are using a ASP.NET MVC project to demonstrate this. So create a new MVC project in Visual Studio.
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==" }
Here we are returning sample base64 data in the method GetBase64Data. Once we finished the coding in controller, We need to do some code changes in the view too.
We can use any view and add our download link to download data file. In the view we can just simply 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 to call the url with Ajax.
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. Once downloaded the file, We can use this site for encoding and decoding base64 data to test this app.