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 check PAN-Aadhaar is Linked or NOT?
- How to customize pagination for django admin?
- How to fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
Related Article