zoukankan      html  css  js  c++  java
  • 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();//将当前所有缓冲区的输出内容发送到客户端,并停止页面的执行
    }

    }

    }

    效果 图

  • 相关阅读:
    ZOJ 3713 In 7-bit (题意不好理解,十进制、二进制、十六进制的转换问题)
    C++ cout 如何保留小数输出
    ZOJ 3705 Applications 模拟
    Google Code Jam Round 1A 2015 Problem B. Haircut 二分
    --算法分析与设计--课程作业--【顺序统计】--【采用链表法散列表】--【开放地址法(双重散列)】
    C++获取当前时间和计算程序运行时间的方法
    【STL__set_的应用】
    ZOJ 3601 Unrequited Love 【STL__pair_的应用】
    Linux概念
    fragment创建
  • 原文地址:https://www.cnblogs.com/shenzhoulong/p/1729419.html
Copyright © 2011-2022 走看看