FileDownUtil.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. using Microsoft.AspNetCore.Http;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using System.Web;
  5. namespace WMS.Util
  6. {
  7. public static class FileDownloadExtensions
  8. {
  9. public static async Task DownloadAsync(this HttpContext context, string fileName, string filePath)
  10. {
  11. if (!File.Exists(filePath))
  12. {
  13. context.Response.StatusCode = StatusCodes.Status404NotFound;
  14. await context.Response.WriteAsync("File not found.");
  15. return;
  16. }
  17. var memory = new MemoryStream();
  18. using var stream = new FileStream(filePath, FileMode.Open);
  19. await stream.CopyToAsync(memory);
  20. memory.Position = 0;
  21. var contentType = GetContentType(filePath);
  22. context.Response.ContentType = contentType;
  23. context.Response.Headers.Add("Content-Disposition", $"attachment; filename={fileName}");
  24. context.Response.StatusCode = StatusCodes.Status200OK;
  25. await context.Response.Body.WriteAsync(memory.ToArray());
  26. }
  27. private static string GetContentType(string path)
  28. {
  29. var types = new Dictionary<string, string>
  30. {
  31. {".txt", "text/plain"},
  32. {".pdf", "application/pdf"},
  33. // add more file types
  34. };
  35. var ext = Path.GetExtension(path).ToLowerInvariant();
  36. return types.ContainsKey(ext) ? types[ext] : "application/octet-stream";
  37. }
  38. }
  39. /// <summary>
  40. /// 描 述:文件下载类
  41. /// </summary>
  42. public class FileDownUtil
  43. {
  44. public FileDownUtil()
  45. { }
  46. // /// <summary>
  47. // /// 参数为虚拟路径
  48. // /// </summary>
  49. // public static string FileNameExtension(string FileName)
  50. // {
  51. // return Path.GetExtension(MapPathFile(FileName));
  52. // }
  53. /// <summary>
  54. /// 获取物理地址
  55. /// </summary>
  56. public static string MapPathFile(string FileName)
  57. {
  58. return ConfigHelper.GetValue<string>("baseDir");
  59. //return Directory.GetCurrentDirectory();
  60. }
  61. // /// <summary>
  62. // /// 验证文件是否存在
  63. // /// </summary>
  64. // /// <param name="FileName"></param>
  65. // /// <returns></returns>
  66. // public static bool FileExists(string FileName)
  67. // {
  68. // string destFileName = FileName;
  69. // if (File.Exists(destFileName))
  70. // {
  71. // return true;
  72. // }
  73. // else
  74. // {
  75. // return false;
  76. // }
  77. // }
  78. // /// <summary>
  79. // /// 普通下载
  80. // /// </summary>
  81. // /// <param name="FileName">文件虚拟路径</param>
  82. // /// /// <param name="name">返回客户端名称</param>
  83. // public static void DownLoadold(string FileName, string name)
  84. // {
  85. // string destFileName = FileName;
  86. // if (File.Exists(destFileName))
  87. // {
  88. // FileInfo fi = new FileInfo(destFileName);
  89. // HttpContext.Current.Response.Clear();
  90. // HttpContext.Current.Response.ClearHeaders();
  91. // HttpContext.Current.Response.Buffer = false;
  92. // HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
  93. // HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
  94. // HttpContext.Current.Response.ContentType = "application/octet-stream";
  95. // HttpContext.Current.Response.WriteFile(destFileName);
  96. // HttpContext.Current.Response.Flush();
  97. // HttpContext.Current.Response.End();
  98. // }
  99. // }
  100. // /// <summary>
  101. // /// 分块下载
  102. // /// </summary>
  103. // /// <param name="FileName">文件虚拟路径</param>
  104. // public static void DownLoad(string FileName)
  105. // {
  106. // string filePath = MapPathFile(FileName);
  107. // long chunkSize = 204800; //指定块大小
  108. // byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
  109. // long dataToRead = 0; //已读的字节数
  110. // FileStream stream = null;
  111. // try
  112. // {
  113. // //打开文件
  114. // stream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
  115. // dataToRead = stream.Length;
  116. // //添加Http头
  117. // HttpContext.Current.Response.ContentType = "application/octet-stream";
  118. // HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
  119. // HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());
  120. // while (dataToRead > 0)
  121. // {
  122. // if (HttpContext.Current.Response.IsClientConnected)
  123. // {
  124. // int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
  125. // HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
  126. // HttpContext.Current.Response.Flush();
  127. // HttpContext.Current.Response.Clear();
  128. // dataToRead -= length;
  129. // }
  130. // else
  131. // {
  132. // dataToRead = -1; //防止client失去连接
  133. // }
  134. // }
  135. // }
  136. // catch (Exception ex)
  137. // {
  138. // HttpContext.Current.Response.Write("Error:" + ex.Message);
  139. // }
  140. // finally
  141. // {
  142. // if (stream != null) stream.Close();
  143. // HttpContext.Current.Response.Close();
  144. // }
  145. // }
  146. // /// <summary>
  147. // /// 分块下载
  148. // /// </summary>
  149. // /// <param name="stream">文件流</param>
  150. // /// <param name="filename">文件名</param>
  151. // public static void DownLoad(MemoryStream stream, string filename)
  152. // {
  153. // long chunkSize = 204800; //指定块大小
  154. // byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
  155. // long dataToRead = 0; //已读的字节数
  156. // try
  157. // {
  158. // dataToRead = stream.Length;
  159. // //添加Http头
  160. // HttpContext.Current.Response.ContentType = "application/octet-stream";
  161. // HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + filename);
  162. // HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());
  163. // while (dataToRead > 0)
  164. // {
  165. // if (HttpContext.Current.Response.IsClientConnected)
  166. // {
  167. // int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
  168. // HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
  169. // HttpContext.Current.Response.Flush();
  170. // HttpContext.Current.Response.Clear();
  171. // dataToRead -= length;
  172. // }
  173. // else
  174. // {
  175. // dataToRead = -1; //防止client失去连接
  176. // }
  177. // }
  178. // }
  179. // catch (Exception ex)
  180. // {
  181. // HttpContext.Current.Response.Write("Error:" + ex.Message);
  182. // }
  183. // finally
  184. // {
  185. // if (stream != null) stream.Close();
  186. // HttpContext.Current.Response.Close();
  187. // }
  188. // }
  189. /// <summary>
  190. /// 下载文件
  191. /// </summary>
  192. /// <param name="filePath">物理地址</param>
  193. public static void DownLoadnew(string filePath)
  194. {
  195. long chunkSize = 204800; //指定块大小
  196. byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区
  197. long dataToRead = 0; //已读的字节数
  198. FileStream stream = null;
  199. try
  200. {
  201. //打开文件
  202. stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  203. dataToRead = stream.Length;
  204. //添加Http头
  205. WebUtil.HttpContext.Response.ContentType = "application/octet-stream";
  206. WebUtil.HttpContext.Response.Headers.Add("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath)));
  207. WebUtil.HttpContext.Response.Headers.Add("Content-Length", dataToRead.ToString());
  208. while (dataToRead > 0)
  209. {
  210. if (WebUtil.HttpContext.Response.HasStarted)
  211. {
  212. int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
  213. WebUtil.HttpContext.Response.Body.Write(buffer, 0, length);
  214. WebUtil.HttpContext.Response.Body.Flush();
  215. WebUtil.HttpContext.Response.Clear();
  216. dataToRead -= length;
  217. }
  218. else
  219. {
  220. dataToRead = -1; //防止client失去连接
  221. }
  222. }
  223. }
  224. catch (Exception ex)
  225. {
  226. //WebUtil.HttpContext.Response.Body.Write("Error:" + ex.Message);
  227. }
  228. finally
  229. {
  230. if (stream != null) stream.Close();
  231. WebUtil.HttpContext.Response.Body.Close();
  232. }
  233. }
  234. // /// <summary>
  235. // /// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
  236. // /// </summary>
  237. // /// <param name="_Request">Page.Request对象</param>
  238. // /// <param name="_Response">Page.Response对象</param>
  239. // /// <param name="_fileName">下载文件名</param>
  240. // /// <param name="_fullPath">带文件名下载路径</param>
  241. // /// <param name="_speed">每秒允许下载的字节数</param>
  242. // /// <returns>返回是否成功</returns>
  243. // //---------------------------------------------------------------------
  244. // //调用:
  245. // // string FullPath=Server.MapPath("count.txt");
  246. // // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100);
  247. // //---------------------------------------------------------------------
  248. // public static bool ResponseFile(HttpContext _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
  249. // {
  250. // try
  251. // {
  252. // FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  253. // BinaryReader br = new BinaryReader(myFile);
  254. // try
  255. // {
  256. // _Response.AddHeader("Accept-Ranges", "bytes");
  257. // _Response.Buffer = false;
  258. // long fileLength = myFile.Length;
  259. // long startBytes = 0;
  260. // int pack = 10240; //10K bytes
  261. // int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
  262. // if (_Request.Headers["Range"] != null)
  263. // {
  264. // _Response.StatusCode = 206;
  265. // string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
  266. // startBytes = Convert.ToInt64(range[1]);
  267. // }
  268. // _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
  269. // if (startBytes != 0)
  270. // {
  271. // _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
  272. // }
  273. // _Response.AddHeader("Connection", "Keep-Alive");
  274. // _Response.ContentType = "application/octet-stream";
  275. // _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
  276. // br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
  277. // int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
  278. // for (int i = 0; i < maxCount; i++)
  279. // {
  280. // if (_Response.IsClientConnected)
  281. // {
  282. // _Response.BinaryWrite(br.ReadBytes(pack));
  283. // Thread.Sleep(sleep);
  284. // }
  285. // else
  286. // {
  287. // i = maxCount;
  288. // }
  289. // }
  290. // }
  291. // catch
  292. // {
  293. // return false;
  294. // }
  295. // finally
  296. // {
  297. // br.Close();
  298. // myFile.Close();
  299. // }
  300. // }
  301. // catch
  302. // {
  303. // return false;
  304. // }
  305. // return true;
  306. // }
  307. }
  308. }