介紹
讓用戶從我們的網(wǎng)站上下載各種類型的文件是一個(gè)比較常用的功能,這篇文章就是告訴您如何創(chuàng)建一個(gè).txt文件并讓用戶下載。
使用代碼
雖然在示例里,我先創(chuàng)建了一個(gè)text文件,但是你不一定也要這么做,因?yàn)檫@個(gè)文件可能在你的網(wǎng)站里已經(jīng)存在了。如果是這樣的話,你只需要使用FileStream去讀取它就可以了。
首先,我們將這個(gè)text文件讀取到一個(gè)byte數(shù)組中,然后使用Response對(duì)象將文件寫到客戶端就可以了。
Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
這段代碼是完成這個(gè)功能的主要代碼。第一句在輸出中添加了一個(gè)Header,告訴瀏覽器我們發(fā)送給它的是一個(gè)附件類型的文件。然后我們?cè)O(shè)置輸出的ContentType是"application/octet-stream",即告訴瀏覽器要下載這個(gè)文件,而不是在瀏覽器中顯示它。
下面是一個(gè)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"
下面是一個(gè)完整的如何下載文本文件的示例代碼
C#
protectedvoid 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 = newbyte[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 AsString = System.IO.Path.GetRandomFileName()
Dim strFriendlyName AsString = "Friendly.txt"
Using sw AsNew System.IO.StreamWriter(Server.MapPath("TextFiles/" + strFileName + ".txt"))
sw.WriteLine(txtText.Text)
sw.Close()
EndUsing
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) AsByte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With Response
.AddHeader("Content-disposition", "attachment;filename=" & strFriendlyName)
.ContentType = "application/octet-stream"
.BinaryWrite(btFile)
.End()
EndWith
小結(jié)
使用這個(gè)方法,你可以實(shí)現(xiàn)在Windows系統(tǒng)下下載所有的文件類型。但是在Macintosh系統(tǒng)下會(huì)有些問題。