In this article, I will show you how to download a file using asp.net c#. Based on the file extension you can set the content type value to be get downloaded. The Response.TransmitFile retrieves file by using file server path and writes to it response.
Here the user can upload the file using file upload control and show it in a label control. When the user clicks the download button it will check whether it is text or pdf or doc or JPEG file and get downloaded as per ContentType.
Download.aspx:
<form id="form1" runat="server">
<div>
<table style="padding: 20px;">
<tr>
<td>
<asp:Label ID="lblFilename" runat="server" Text="Browse:"></asp:Label>
</td>
<td>
<asp:FileUpload ID="fileUpload1" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<asp:LinkButton runat="server" OnClick="lnkUpload_Click" Font-Underline="False">Upload</asp:LinkButton>
</td>
<td>
<asp:LinkButton runat="server" OnClick="lnkDownload_Click" Font-Underline="False">Download</asp:LinkButton>
</td>
</tr>
</table>
</div>
</form>
Download.aspx.cs:
protected void lnkUpload_Click(object sender, EventArgs e)
{
filename= Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Uploads/" + filename));
Response.Write("Fileuploaded sucessfully.");
lblFilename.Text = "Uploads/" + fileUpload1.FileName;
}
// To download uplaoded file
protected void lnkDownload_Click(object sender, EventArgs e)
{
if (lblFilename.Text != string.Empty)
{
if (lblFilename.Text.EndsWith(".txt"))
{
Response.ContentType = "application/txt";
}
else if (lblFilename.Text.EndsWith(".pdf"))
{
Response.ContentType = "application/pdf";
}
else if (lblFilename.Text.EndsWith(".docx"))
{
Response.ContentType = "application/docx";
}
else
{
Response.ContentType = "image/jpg";
}
string filePath = lblFilename.Text;
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
Download file to client PC:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article