从网页创建和下载文本文件






3.06/5 (16投票s)
本文将演示如何创建和查看一个文本文件。
引言
在 Web 应用程序中,通常需要将某种文件下载到客户端计算机的功能。本文将说明如何创建并将文本文件下载到用户的计算机。
使用代码
虽然在示例中,我实际上在将文本文件流式传输到客户端之前创建它,但我认为强调一下,你并不一定需要这样做,因为该文件实际上可能存在于文件系统中,并且你可能希望将其流式传输到客户端。如果是这样,你可能需要使用 FileStream
来读取已经存在的文档。
我们首先打开文件进行读取,并实际逐字节将文件读取到流中,然后一旦将文件放入流中,我们只需使用 Response
对象并通过输出流下载文件。
Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
此代码片段的真正威力在于上面的几行代码;通过添加一个标头,你告诉浏览器将文件作为附件下载。然后你设置 ContentType
标头,该标头被添加,并设置你的 MIME
类型,以便浏览器知道它即将下载哪种类型的文件。你可以为浏览器选择以下任何 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"
'Handle All Other Files
= "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 系统存在一些问题。具体来说,你可能无法下载文件,而是它们将像预期一样在浏览器中打开。