Introduction
ASP.NET is an open-source web framework that works on the server-side to produce dynamic web pages using HTML, CSS, JavaScript, TypeScript. ASP.NET supports the download, upload, and delete file functionality. Let’s discuss about the functionality of downloading a file further in this article.
You might have downloaded a lot of files from browsers like projects, assignment references. But have you ever wondered how the downloading functionality works and what the code might look like behind it? Let’s learn the functionality and code now.
File Download
ASP.NET provides us with implicit object Response and methods to download a file from the server. We can add the downloading feature to our application by adding these methods to our code.
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="FileDownloadExample._Default" %>
<!DOCTYPE html>
<script>
protected void BtnClick(object sender, EventArgs e) {
string filePath = (sender as Button).CommandArgument;
Response.ContentType = ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
Response.WriteFile(filePath);
Response.End();
}
</script>
<form id="form1" runat="server">
<p>Download a file</p>
<asp:Button ID="Btn" runat="server" OnClick="BtnClick" Text="Download" CommandArgument = '<%# Eval("Value") %>'/>
<br/>
<br/>
<asp:Label ID="labelId" runat="server"></asp:Label>
</form>
The following popup opens on your system when you click on the download button.
In the above code, we created an ASP button with text download on it. When the user clicks on it the method fetches the link of the file using the object and commandArgument property of the button. Finally, using the writeFile method, the file is written to the response stream and downloaded.
In the above code, we created an ASP button with text download on it. When the user clicks on it the method fetches the link of the file using the object and commandArgument property of the button. Finally, using the writeFile method, the file is written to the response stream and downloaded.