//引用命名空间
using System.IO;
using System.Text;
using System.Web;
// 文件下载
public static bool DownloadFile(string path)
{
HttpRequest request = HttpContext.Current.Request;
HttpResponse response = HttpContext.Current.Response;
try
{
FileInfo info = new FileInfo(HttpContext.Current.Server.MapPath(path));
if (info.Exists)
{
string name = info.Name;
string extension = info.Extension;
name = name.Substring(0, name.Length - extension.Length);
while (HttpUtility.UrlEncode(name + extension, Encoding.UTF8).Length > 0x9c)
{
name = name.Substring(0, name.Length - 1);
}
name = HttpUtility.UrlEncode(name + extension, Encoding.UTF8);
response.Clear();
if (info.Length < 0xfa000L)
{
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment;filename=" + name);
response.WriteFile(info.FullName);
}
else
{
FileStream input = new FileStream(HttpContext.Current.Server.MapPath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader reader = new BinaryReader(input);
try
{
long length = input.Length;
long num2 = 0L;
int count = 0x2800;
if (request.Headers["Range"] != null)
{
response.StatusCode = 0xce;
num2 = Convert.ToInt64(request.Headers["Range"].Split(new char[] { '=', '-' })[1]);
}
response.AddHeader("Content-Length", (length - num2).ToString());
if (num2 != 0L)
{
response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", num2, length - 1L, length));
}
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment;filename=" + name);
reader.BaseStream.Seek(num2, SeekOrigin.Begin);
int num4 = ((int)Math.Floor((double)(((double)(length - num2)) / ((double)count)))) + 1;
for (int i = 0; i < num4; i++)
{
if (response.IsClientConnected)
{
response.BinaryWrite(reader.ReadBytes(count));
response.Flush();
}
else
{
i = num4;
}
}
}
catch
{
return false;
}
finally
{
reader.Close();
input.Close();
}
}
}
}
catch (Exception)
{
return false;
}
return true;
}
文件下载
最新推荐文章于 2022-11-23 19:23:01 发布