123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329 |
- using Microsoft.AspNetCore.Http;
- using System.IO;
- using System.Threading.Tasks;
- using System.Web;
- namespace WMS.Util
- {
- public static class FileDownloadExtensions
- {
- public static async Task DownloadAsync(this HttpContext context, string fileName, string filePath)
- {
- if (!File.Exists(filePath))
- {
- context.Response.StatusCode = StatusCodes.Status404NotFound;
- await context.Response.WriteAsync("File not found.");
- return;
- }
- var memory = new MemoryStream();
- using var stream = new FileStream(filePath, FileMode.Open);
- await stream.CopyToAsync(memory);
- memory.Position = 0;
- var contentType = GetContentType(filePath);
- context.Response.ContentType = contentType;
- context.Response.Headers.Add("Content-Disposition", $"attachment; filename={fileName}");
- context.Response.StatusCode = StatusCodes.Status200OK;
- await context.Response.Body.WriteAsync(memory.ToArray());
- }
- private static string GetContentType(string path)
- {
- var types = new Dictionary<string, string>
- {
- {".txt", "text/plain"},
- {".pdf", "application/pdf"},
- // add more file types
- };
- var ext = Path.GetExtension(path).ToLowerInvariant();
- return types.ContainsKey(ext) ? types[ext] : "application/octet-stream";
- }
- }
- /// <summary>
- /// 描 述:文件下载类
- /// </summary>
- public class FileDownUtil
- {
- public FileDownUtil()
- { }
- // /// <summary>
- // /// 参数为虚拟路径
- // /// </summary>
- // public static string FileNameExtension(string FileName)
- // {
- // return Path.GetExtension(MapPathFile(FileName));
- // }
- /// <summary>
- /// 获取物理地址
- /// </summary>
- public static string MapPathFile(string FileName)
- {
- return ConfigHelper.GetValue<string>("baseDir");
- //return Directory.GetCurrentDirectory();
- }
- // /// <summary>
- // /// 验证文件是否存在
- // /// </summary>
- // /// <param name="FileName"></param>
- // /// <returns></returns>
- // public static bool FileExists(string FileName)
- // {
- // string destFileName = FileName;
- // if (File.Exists(destFileName))
- // {
- // return true;
- // }
- // else
- // {
- // return false;
- // }
- // }
- // /// <summary>
- // /// 普通下载
- // /// </summary>
- // /// <param name="FileName">文件虚拟路径</param>
- // /// /// <param name="name">返回客户端名称</param>
- // public static void DownLoadold(string FileName, string name)
- // {
- // string destFileName = FileName;
- // if (File.Exists(destFileName))
- // {
- // FileInfo fi = new FileInfo(destFileName);
- // HttpContext.Current.Response.Clear();
- // HttpContext.Current.Response.ClearHeaders();
- // HttpContext.Current.Response.Buffer = false;
- // HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
- // HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
- // HttpContext.Current.Response.ContentType = "application/octet-stream";
- // HttpContext.Current.Response.WriteFile(destFileName);
- // HttpContext.Current.Response.Flush();
- // HttpContext.Current.Response.End();
- // }
- // }
- // /// <summary>
- // /// 分块下载
- // /// </summary>
- // /// <param name="FileName">文件虚拟路径</param>
- // public static void DownLoad(string FileName)
- // {
- // string filePath = MapPathFile(FileName);
- // long chunkSize = 204800; //指定块大小
- // byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
- // long dataToRead = 0; //已读的字节数
- // FileStream stream = null;
- // try
- // {
- // //打开文件
- // stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
- // dataToRead = stream.Length;
- // //添加Http头
- // HttpContext.Current.Response.ContentType = "application/octet-stream";
- // HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
- // HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());
- // while (dataToRead > 0)
- // {
- // if (HttpContext.Current.Response.IsClientConnected)
- // {
- // int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
- // HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
- // HttpContext.Current.Response.Flush();
- // HttpContext.Current.Response.Clear();
- // dataToRead -= length;
- // }
- // else
- // {
- // dataToRead = -1; //防止client失去连接
- // }
- // }
- // }
- // catch (Exception ex)
- // {
- // HttpContext.Current.Response.Write("Error:" + ex.Message);
- // }
- // finally
- // {
- // if (stream != null) stream.Close();
- // HttpContext.Current.Response.Close();
- // }
- // }
- // /// <summary>
- // /// 分块下载
- // /// </summary>
- // /// <param name="stream">文件流</param>
- // /// <param name="filename">文件名</param>
- // public static void DownLoad(MemoryStream stream, string filename)
- // {
- // long chunkSize = 204800; //指定块大小
- // byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
- // long dataToRead = 0; //已读的字节数
- // try
- // {
- // dataToRead = stream.Length;
- // //添加Http头
- // HttpContext.Current.Response.ContentType = "application/octet-stream";
- // HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + filename);
- // HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());
- // while (dataToRead > 0)
- // {
- // if (HttpContext.Current.Response.IsClientConnected)
- // {
- // int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
- // HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
- // HttpContext.Current.Response.Flush();
- // HttpContext.Current.Response.Clear();
- // dataToRead -= length;
- // }
- // else
- // {
- // dataToRead = -1; //防止client失去连接
- // }
- // }
- // }
- // catch (Exception ex)
- // {
- // HttpContext.Current.Response.Write("Error:" + ex.Message);
- // }
- // finally
- // {
- // if (stream != null) stream.Close();
- // HttpContext.Current.Response.Close();
- // }
- // }
- /// <summary>
- /// 下载文件
- /// </summary>
- /// <param name="filePath">物理地址</param>
- public static void DownLoadnew(string filePath)
- {
- long chunkSize = 204800; //指定块大小
- byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
- long dataToRead = 0; //已读的字节数
- FileStream stream = null;
- try
- {
- //打开文件
- stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
- dataToRead = stream.Length;
- //添加Http头
- WebUtil.HttpContext.Response.ContentType = "application/octet-stream";
- WebUtil.HttpContext.Response.Headers.Add("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
- WebUtil.HttpContext.Response.Headers.Add("Content-Length", dataToRead.ToString());
- while (dataToRead > 0)
- {
- if (WebUtil.HttpContext.Response.HasStarted)
- {
- int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
- WebUtil.HttpContext.Response.Body.Write(buffer, 0, length);
- WebUtil.HttpContext.Response.Body.Flush();
- WebUtil.HttpContext.Response.Clear();
- dataToRead -= length;
- }
- else
- {
- dataToRead = -1; //防止client失去连接
- }
- }
- }
- catch (Exception ex)
- {
- //WebUtil.HttpContext.Response.Body.Write("Error:" + ex.Message);
- }
- finally
- {
- if (stream != null) stream.Close();
- WebUtil.HttpContext.Response.Body.Close();
- }
- }
- // /// <summary>
- // /// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
- // /// </summary>
- // /// <param name="_Request">Page.Request对象</param>
- // /// <param name="_Response">Page.Response对象</param>
- // /// <param name="_fileName">下载文件名</param>
- // /// <param name="_fullPath">带文件名下载路径</param>
- // /// <param name="_speed">每秒允许下载的字节数</param>
- // /// <returns>返回是否成功</returns>
- // //---------------------------------------------------------------------
- // //调用:
- // // string FullPath=Server.MapPath("count.txt");
- // // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100);
- // //---------------------------------------------------------------------
- // public static bool ResponseFile(HttpContext _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
- // {
- // try
- // {
- // FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
- // BinaryReader br = new BinaryReader(myFile);
- // try
- // {
- // _Response.AddHeader("Accept-Ranges", "bytes");
- // _Response.Buffer = false;
- // long fileLength = myFile.Length;
- // long startBytes = 0;
- // int pack = 10240; //10K bytes
- // int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
- // if (_Request.Headers["Range"] != null)
- // {
- // _Response.StatusCode = 206;
- // string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
- // startBytes = Convert.ToInt64(range[1]);
- // }
- // _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
- // if (startBytes != 0)
- // {
- // _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
- // }
- // _Response.AddHeader("Connection", "Keep-Alive");
- // _Response.ContentType = "application/octet-stream";
- // _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
- // br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
- // int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
- // for (int i = 0; i < maxCount; i++)
- // {
- // if (_Response.IsClientConnected)
- // {
- // _Response.BinaryWrite(br.ReadBytes(pack));
- // Thread.Sleep(sleep);
- // }
- // else
- // {
- // i = maxCount;
- // }
- // }
- // }
- // catch
- // {
- // return false;
- // }
- // finally
- // {
- // br.Close();
- // myFile.Close();
- // }
- // }
- // catch
- // {
- // return false;
- // }
- // return true;
- // }
- }
- }
|