在ASP.NET中下载Text文件,而不是在浏览器中打开它

添加人:iyond六级(3296分)   添加时间:2007-06-13    阅读次数:1216  收藏此教程

介绍

让用户从我们的网站上下载各种类型的文件是一个比较常用的功能,这篇文章就是告诉您如何创建一个.txt文件并让用户下载。

使用代码

虽然在示例里,我先创建了一个text文件,但是你不一定也要这么做,因为这个文件可能在你的网站里已经存在了。如果是这样的话,你只需要使用FileStream去读取它就可以了。

首先,我们将这个text文件读取到一个byte数组中,然后使用Response对象将文件写到客户端就可以了。

Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(btFile);
        Response.End();


这段代码是完成这个功能的主要代码。第一句在输出中添加了一个Header,告诉浏览器我们发送给它的是一个附件类型的文件。然后我们设置输出的ContentType是"application/octet-stream",即告诉浏览器要下载这个文件,而不是在浏览器中显示它。

下面是一个MIME类型的列表。
 ".asf" = "video/x-ms-asf"
 ".avi" = "video/avi"
 ".doc" = "application/msword"
 ".zip" = "application/zip"
 ".xls" = "application/vnd.ms-excel"
 ".gif" = "image/gif"
 ".jpg"= "image/jpeg"
 ".wav" = "audio/wav"
 ".mp3" = "audio/mpeg3"
 ".mpg" "mpeg" = "video/mpeg"
 ".rtf" = "application/rtf"
 ".htm", "html" = "text/html"
 ".asp" = "text/asp"
 
'所有其它的文件
 = "application/octet-stream"

下面是一个完整的如何下载文本文件的示例代码
C#
 
protected void Button1_Click(object sender, EventArgs e)
{
    string sFileName = System.IO.Path.GetRandomFileName();
    string sGenName = "Friendly.txt";
    //YOu could omit these lines here as you may not want to save the textfile to the server
    //I have just left them here to demonstrate that you could create the text file
    using (System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("TextFiles/" + sFileName + ".txt")))
    {
        SW.WriteLine(txtText.Text);
        SW.Close();
    }

    System.IO.FileStream fs = null;
    fs = System.IO.File.Open(Server.MapPath("TextFiles/" + sFileName + ".txt"), System.IO.FileMode.Open);
    byte[] btFile = new byte[fs.Length];
    fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
    fs.Close();
    Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
    Response.ContentType = "application/octet-stream";
    Response.BinaryWrite(btFile);
    Response.End();
}


 
VB.NET
Dim strFileName As String = System.IO.Path.GetRandomFileName()
Dim strFriendlyName As String = "Friendly.txt"

Using sw As New System.IO.StreamWriter(Server.MapPath("TextFiles/" + strFileName + ".txt"))
    sw.WriteLine(txtText.Text)
    sw.Close()
End Using

Dim fs As System.IO.FileStream = Nothing


fs = System.IO.File.Open(Server.MapPath("TextFiles/" + strFileName + ".txt"), System.IO.FileMode.Open)
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With Response
    .AddHeader("Content-disposition", "attachment;filename=" & strFriendlyName)
    .ContentType = "application/octet-stream"
    .BinaryWrite(btFile)
    .End()
End With

  小结
使用这个方法,你可以实现在Windows系统下下载所有的文件类型。但是在Macintosh系统下会有些问题。
 
1页 第1上一页1下一页
相关的教程: 下载文件 文本文件
收藏此教程

当前平均分: 0.0(0 次打分)

-5-4-3-2-1012345
评论主题
您的大名
您的评论
验证码 点击换一个验证码
知识库搜索: