以上文章转贴自http://www.w269.com/infow269/1145w2691.htm
这里我想讨论一下,这么也东东。
Q:如何利用ContentType 来,在服务器上提供一个.xls后缀的文件点击下载而不是直接在浏览器中打开。(注意:于上程序文件以XLS文件被提供下载有所不同)
Response.ContentType = "application/x-download",让整个程序文件点击下载了。怎么办好呢???
A:解决方案1. 利用Response.WriteFile的文件输出操作
具体在按钮点击事件中添加一下代码
private void btnDownload_Click(object sender, System.EventArgs e)
{
string DownloadFileName=Server.MapPath("file.xls");
string filepath = DownloadFileName;
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
Response.Clear();
// Specify the Type of the downloadable file.
Response.ContentType = "application/octet-stream";
// Set the Default file name in the FileDownload dialog box.
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.Flush();
// Download the file.
Response.WriteFile(filepath);
}
以上代码也适合用于小于100MB的小文件下载
如果是大于100MB的大文件下载可以用Response.FileStream 。
C#代码如下:(将 DownloadFileName 替换为大于 100 MB 的文件的名称。)
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
// Identify the file to download including its path.
string filepath = "DownloadFileName";
// Identify the file name.
string filename = System.IO.Path.GetFileName(filepath);
try
{
// Open the file.
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
System.IO.FileAccess.Read,System.IO.FileShare.Read);//用文件流来处理
// Total bytes to read:
dataToRead = iStream.Length;
Response.ContentType = "application/octet-stream";//问题就在这里,解决百M关口
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
Response.Flush();
buffer= new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
参考:PRB:Response.WriteFile 无法下载大文件
http://support.microsoft.com/default.aspx?scid=kb;zh-cn;812406#2
本文地址:http://com.8s8s.com/it/it41872.htm