本文概述
- ASP.NET下载文件示例
- 码
在这里,我们正在创建一个示例,允许我们下载文件。
ASP.NET下载文件示例// Default.aspx
<
%@ Page Title="Home Page" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="FileDownloadExample._Default" %>
<
form id="form1" runat="server">
<
p>
Click the button to download a file<
/p>
<
asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Download" />
<
br />
<
br />
<
asp:Label ID="Label1" runat="server"><
/asp:Label>
<
/form>
码// Default.aspx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FileDownloadExample
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string filePath = "C:\\Users\\Admi\\Desktop\\abc.txt";
FileInfo file = new FileInfo(filePath);
if (file.Exists)
{
// Clear Rsponse reference
Response.Clear();
// Add header by specifying file name
Response.AddHeader("Content-Disposition", "attachment;
filename=" + file.Name);
// Add header for content length
Response.AddHeader("Content-Length", file.Length.ToString());
// Specify content type
Response.ContentType = "text/plain";
// Clearing flush
Response.Flush();
// Transimiting file
Response.TransmitFile(file.FullName);
Response.End();
}
else Label1.Text = "Requested file is not available to download";
}
}
}
【asp.net下载文件】输出:
文章图片
该应用程序将提示一个窗口,以从服务器下载文件。
文章图片
推荐阅读
- asp.net cookie使用
- asp.net上传多个文件
- asp.net web表单文件上传fileupload
- asp.net linkbutton用法
- asp.net复选框
- asp.net web表单日历
- asp.net radiobutton用法
- asp.net超链接
- asp.net按钮