In this article I will explain with an example, how to download File using jQuery AJAX in ASP.Net MVC Razor.
This article will illustrate how to download File from Folder (Directory) using jQuery AJAX in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Location of Files
The Files i.e., Word document, Excel file and PDF file are stored in a folder named Files inside the project directory.
ASP.Net MVC: Download File using jQuery AJAX
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling jQuery AJAX File Download operation
This Action method handles the GET call made from the jQuery AJAX function from the View.
The DownloadFile Action method accepts the name of the File to be downloaded as parameter.
First, the Path of the Files folder is generated and then the File is read as Byte Array (Binary Data) from the folder using the ReadAllBytes function of the File class.
Note: Since Files are downloaded as Base64 string, hence the return type is set to ContentResult.
 
Finally, the Byte Array is converted into Base64 string and returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ContentResult DownloadFile(string fileName)
    {
        //Set the File Folder Path.
        string path = Server.MapPath("~/Files/");
 
        //Read the File as Byte Array.
        byte[] bytes = System.IO.File.ReadAllBytes(path + fileName);
 
        //Convert File to Base64 string and send to Client.
        string base64 = Convert.ToBase64String(bytes, 0, bytes.Length);
 
        return Content(base64);
    }
}
 
 
View
The View consists of 3 HTML Buttons for downloading the 3 types of File i.e. Word document, Excel file and PDF file and each Button has been assigned with a JavaScript OnClick event handler.
When any of the three Button is clicked, the DownloadFile JavaScript function is called and the name of the File is passed to it.
Inside the DownloadFile JavaScript function, the name of the File is passed as parameter while calling the Controller’s Action method using jQuery AJAX function.
Then inside the success event handler, the file is converted back to Byte Array (Binary Data) using the Base64ToBytes JavaScript function.
Finally, the Byte Array (Binary Data) is converted to BLOB object and the File is downloaded in Browser.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type="button" value="Download Word File" onclick="DownloadFile('Sample.docx')"/>
    <input type="button" value="Download Excel File" onclick="DownloadFile('Sample.xlsx')"/>
    <input type="button" value="Download PDF File" onclick="DownloadFile('Sample.pdf')"/>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        function DownloadFile(fileName) {
            $.ajax({
                type: "POST",
                url: "/Home/DownloadFile",
                data: '{fileName: "' + fileName + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function (r) {
                    //Convert Base64 string to Byte Array.
                    var bytes = Base64ToBytes(r);
 
                    //Convert Byte Array to BLOB.
                    var blob = new Blob([bytes], { type: "application/octetstream" });
 
                    //Check the Browser type and download the File.
                    var isIE = false || !!document.documentMode;
                    if (isIE) {
                        window.navigator.msSaveBlob(blob, fileName);
                    } else {
                        var url = window.URL || window.webkitURL;
                        link = url.createObjectURL(blob);
                        var a = $("<a />");
                        a.attr("download", fileName);
                        a.attr("href", link);
                        $("body").append(a);
                        a[0].click();
                        $("body").remove(a);
                    }
                }
            });
        };
        function Base64ToBytes(base64) {
            var s = window.atob(base64);
            var bytes = new Uint8Array(s.length);
            for (var i = 0; i < s.length; i++) {
                bytes[i] = s.charCodeAt(i);
            }
            return bytes;
        };
    </script>
</body>
</html>
 
 
Screenshot
ASP.Net MVC: Download File using jQuery AJAX
 
 
Browser Compatibility

The above code has been tested in the following browsers only in versions that support HTML5.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
 
Downloads