对文件下载的补充
我在ASP.NET中常用的文件上传下载方法一文中写了几种文件上传下载的方法,其中第二部分的下载当时没有具体说清楚,现在补充一下。对于有具体物理路径的文件下载,我们可以采用下面的思路,先将其转化成二进制流,然后用浏览器读出来,具体代码如下:
/// <summary>
/// 下载文件
/// </summary>
/// <param name="path">文件所在的物理路径</param>
/// <param name="fileName">文件名称</param>
/// <param name="contentType">客户端MIME类型</param>
private void UpLoadFile(string path, string fileName, string contentType)
{
FileInfo fi = new FileInfo(path);
FileStream fs = fi.OpenRead();
byte[] FileArray = new byte[(int)fs.Length];
fs.Read(FileArray, 0, FileArray.Length);
fs.Close();
Response.Buffer = true;
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(FileArray);
Response.Flush();
Response.End();
}
/// 下载文件
/// </summary>
/// <param name="path">文件所在的物理路径</param>
/// <param name="fileName">文件名称</param>
/// <param name="contentType">客户端MIME类型</param>
private void UpLoadFile(string path, string fileName, string contentType)
{
FileInfo fi = new FileInfo(path);
FileStream fs = fi.OpenRead();
byte[] FileArray = new byte[(int)fs.Length];
fs.Read(FileArray, 0, FileArray.Length);
fs.Close();
Response.Buffer = true;
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.BinaryWrite(FileArray);
Response.Flush();
Response.End();
}
posted on 2007-03-13 18:05 Daniel Pang 阅读(1360) 评论(5) 编辑 收藏 举报