文件下载

#region
/// <summary>
///
/// </summary>
/// <param name="path">路径</param>
/// <param name="context"></param>
/// <param name="hasfileName">true的时候就用当前时间命名</param>
public void ResponseFile(string path, HttpContext context, bool hasfileName)
{
context = HttpContext.Current;

System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
string filename;
if (!hasfileName)
{
filename = System.IO.Path.GetFileName(path); //获取原来的文件名
}
else
{
filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip";
}

try
{
iStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));

while (dataToRead > 0)
{
if (context.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
context.Response.OutputStream.Write(buffer, 0, length);
context.Response.Flush();

buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception ex)
{
context.Response.Write(ex.Message);
}
finally
{
if (iStream != null)
{
iStream.Close();
}
}
}
#endregion

posted @ 2017-01-12 15:26  二环东路  阅读(113)  评论(0编辑  收藏  举报