In this article I will explain with an example, how to download File using jQuery AJAX in ASP.Net with C# and VB.Net.
This article will illustrate how to download a file using jQuery AJAX with the help of WebMethod in ASP.Net.
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.
HTML Markup
The HTML Markup consists of 3 buttons for downloading the 3 types of File i.e. Word document, Excel file and PDF file.
<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')" />
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Web.Services;
VB.Net
Imports System.IO
Imports System.Web.Services
WebMethod
The WebMethod 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.
Finally, the Byte Array is converted into Base64 string and returned.
C#
[WebMethod]
public static string DownloadFile(string fileName)
{
//Set the File Folder Path.
string path = HttpContext.Current.Server.MapPath("~/Files/");
//Read the File as Byte Array.
byte[] bytes = File.ReadAllBytes(path + fileName);
//Convert File to Base64 string and send to Client.
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
VB.Net
<WebMethod()>
Public Shared Function DownloadFile(ByVal fileName As String) As String
'Set the File Folder Path.
Dim path As String = HttpContext.Current.Server.MapPath("~/Files/")
'Read the File as Byte Array.
Dim bytes As Byte() = File.ReadAllBytes(path & fileName)
'Convert File to Base64 string and send to Client.
Return Convert.ToBase64String(bytes, 0, bytes.Length)
End Function
Downloading File using jQuery AJAX in ASP.Net
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 WebMethod 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.
<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: "Default.aspx/DownloadFile",
data: '{fileName: "' + fileName + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
//Convert Base64 string to Byte Array.
var bytes = Base64ToBytes(r.d);
//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>
Web.Config Setting
You will need to set the maxJsonLength property through Web.Config configuration using the system.web.extensions section as shown below.
This is required as the size of the JSON response exceeds the default value when Files in Base64 string format are downloaded.
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="819200000" />
</webServices>
</scripting>
</system.web.extensions>
Screenshot
Demo
Downloads