c# response输出文件实例(14)
生活随笔
收集整理的這篇文章主要介紹了
c# response输出文件实例(14)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Response.WriteFile方法可以將指定的文件直接寫入HTTP內容輸出流中顯示。
示例是將文件直接輸出到客戶端,html主體代碼:
?
<body><p>
選擇輸出文件:</p>
<form id="form1" runat="server">
<p>
<asp:DropDownList ID="DropDownList1" runat="server" Height="16px" Width="303px">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="輸出文件" />
</p>
<div>
</div>
</form>
</body>
?
?
c#后臺代碼:
?
?
代碼 using System;using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text;
namespace response
{
public partial class _Default : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DropDownList DropDownList;
protected System.Web.UI.WebControls.Button Button;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{//首次加載時獲取站點下的files目錄下的文件及其路徑
string[] files=Directory.GetFiles(Server.MapPath("./files/"));// 創建本地路徑,以映射到服務器的物理路徑
for (int i = 0; i < files.Length; i++)
{//通過循環把服務器的內容添加到DropDownList1
DropDownList1.Items.Add(files[i]);//用add方法將這些文件添加到控件 DropDownList1中
}
}
}
#region web 窗口設計器生成的代碼
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Button1.Click+=new EventHandler(this.Button1_Click);
this.Load += new EventHandler(this.Page_Load);
}
#endregion
private void Button1_Click(object sender, System.EventArgs e)
{//單擊按鈕式觸發的事件
string filename = DropDownList1.SelectedItem.Text;//獲取用戶選擇的文件輸出名稱
FileInfo file = new FileInfo(filename);//創建一個文件對象
Response.Clear();//清除所有緩存區的內容
Response.Charset = "GB2312";//定義輸出字符集
Response.ContentEncoding = Encoding.Default;//輸出內容的編碼為默認編碼
Response.AddHeader("Content-Disposition","attachment;filename="+file.Name);//添加頭信息。為“文件下載/另存為”指定默認文件名稱
Response.AddHeader("Content-Length",file.Length.ToString());//添加頭文件,指定文件的大小,讓瀏覽器顯示文件下載的速度
Response.WriteFile(file.FullName);// 把文件流發送到客戶端
Response.End();//將當前所有緩沖區的輸出內容發送到客戶端,并停止頁面的執行
}
}
}
效果 圖
轉載于:https://www.cnblogs.com/shenzhoulong/archive/2010/05/07/1729419.html
總結
以上是生活随笔為你收集整理的c# response输出文件实例(14)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ 1287题
- 下一篇: android入门之三【应用程序组成】