FileUploadHelper.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Web;
  6. using System.IO;
  7. using System.Web.UI;
  8. using System.Web.Mvc;
  9. using Bowin.Common;
  10. using Ionic.Zip;
  11. namespace EMIS.Utility
  12. {
  13. public class FileUploadHelper
  14. {
  15. private const long BUFFER_SIZE = 4096;
  16. public class RemoteFileInfo
  17. {
  18. public string FileName { get; set; }
  19. public string RemotePath { get; set; }
  20. }
  21. /// <summary>
  22. /// 查询上传文件对应的FileUploadSessionName
  23. /// </summary>
  24. /// <param name="formID"></param>
  25. /// <returns></returns>
  26. public static string GetFileUploadSessionName(Guid formID)
  27. {
  28. return Const.UPLOAD_SESSION_NAME + "_" + formID.ToString();
  29. }
  30. /// <summary>
  31. /// 查询文件上传对应的TagetPhysicalPath(不带文件名及后缀名)
  32. /// </summary>
  33. /// <param name="savePath"></param>
  34. /// <returns></returns>
  35. public static string GetFileUploadTagetPhysicalPath(string savePath = null)
  36. {
  37. string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
  38. string physicalPath = HttpContext.Current.Server.MapPath(filePath);
  39. string dayFolderName = DateTime.Today.ToString("yyyy-MM");
  40. string tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\") + dayFolderName + "\\";
  41. if (!string.IsNullOrEmpty(savePath))
  42. {
  43. filePath += "/" + savePath;
  44. physicalPath = HttpContext.Current.Server.MapPath(filePath);
  45. tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\");
  46. }
  47. if (!Directory.Exists(tagetPhysicalPath))
  48. {
  49. Directory.CreateDirectory(tagetPhysicalPath);
  50. }
  51. return tagetPhysicalPath;
  52. }
  53. /// <summary>
  54. /// 文件上传
  55. /// savePath是相对与web上传路径的子路径
  56. /// 如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
  57. /// </summary>
  58. /// <param name="file"></param>
  59. /// <param name="savePath"></param>
  60. /// <returns></returns>
  61. public static string UploadFileInternal(HttpPostedFileBase file, string savePath = null)
  62. {
  63. if (file == null || string.IsNullOrEmpty(file.FileName)) return null;
  64. UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
  65. string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
  66. string physicalPath = HttpContext.Current.Server.MapPath(filePath);
  67. string dayFolderName = DateTime.Today.ToString("yyyy-MM");
  68. string tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\") + dayFolderName + "\\";
  69. if (!string.IsNullOrEmpty(savePath))
  70. {
  71. filePath += "/" + savePath;
  72. physicalPath = HttpContext.Current.Server.MapPath(filePath);
  73. tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\");
  74. }
  75. if (!Directory.Exists(tagetPhysicalPath))
  76. {
  77. Directory.CreateDirectory(tagetPhysicalPath);
  78. }
  79. var newFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
  80. var physicalFileName = tagetPhysicalPath + newFileName;
  81. file.SaveAs(physicalFileName);
  82. return physicalFileName;
  83. }
  84. /// <summary>
  85. /// 文件上传
  86. /// savePath是相对与web上传路径的子路径
  87. /// 如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
  88. /// </summary>
  89. /// <param name="file"></param>
  90. /// <param name="fileSourceWebPath"></param>
  91. /// <param name="errorSourceWebPath"></param>
  92. /// <param name="savePath"></param>
  93. /// <returns></returns>
  94. public static string UploadFileInternal(HttpPostedFileBase file, out string fileSourceWebPath,
  95. out string errorSourceWebPath, string savePath = null)
  96. {
  97. fileSourceWebPath = null;
  98. errorSourceWebPath = null;
  99. if (file == null || string.IsNullOrEmpty(file.FileName)) return null;
  100. UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
  101. string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
  102. string physicalPath = HttpContext.Current.Server.MapPath(filePath);
  103. string dayFolderName = DateTime.Today.ToString("yyyy-MM");
  104. string tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\") + dayFolderName + "\\";
  105. if (!string.IsNullOrEmpty(savePath))
  106. {
  107. filePath += "/" + savePath;
  108. physicalPath = HttpContext.Current.Server.MapPath(filePath);
  109. tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\");
  110. }
  111. else
  112. {
  113. filePath += "/" + dayFolderName;
  114. }
  115. if (!Directory.Exists(tagetPhysicalPath))
  116. {
  117. Directory.CreateDirectory(tagetPhysicalPath);
  118. }
  119. var newFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
  120. var physicalFileName = tagetPhysicalPath + newFileName;
  121. fileSourceWebPath = urlHelper.Content(filePath + "/" + newFileName);
  122. errorSourceWebPath = urlHelper.Content(filePath + "/" + Guid.NewGuid().ToString() + ".xls");
  123. file.SaveAs(physicalFileName);
  124. return physicalFileName;
  125. }
  126. /// <summary>
  127. /// 删除FileInternal
  128. /// </summary>
  129. /// <param name="filePath"></param>
  130. public static void DeleteFileInternal(string filePath)
  131. {
  132. string fullPath = HttpContext.Current.Server.MapPath("~" + filePath);
  133. File.Delete(fullPath);
  134. }
  135. /// <summary>
  136. /// 文件上传
  137. /// savePath是相对与web上传路径的子路径
  138. /// 如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
  139. /// </summary>
  140. /// <param name="file"></param>
  141. /// <param name="savePath"></param>
  142. /// <returns></returns>
  143. public static string UploadFile(HttpPostedFileBase file, string savePath = null)
  144. {
  145. if (file == null || string.IsNullOrEmpty(file.FileName)) return null;
  146. UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
  147. string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
  148. string dayFolderName = DateTime.Today.ToString("yyyy-MM");
  149. var physicalFileName = UploadFileInternal(file, savePath);
  150. if (!string.IsNullOrEmpty(savePath))
  151. {
  152. filePath += "/" + savePath;
  153. }
  154. else
  155. {
  156. filePath += "/" + dayFolderName;
  157. }
  158. var webFileName = filePath + "/" + Path.GetFileName(physicalFileName);
  159. return urlHelper.Content(webFileName);
  160. }
  161. /// <summary>
  162. /// 批量文件上传
  163. /// savePath是相对与web上传路径的子路径
  164. /// 如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
  165. /// </summary>
  166. /// <param name="fileList"></param>
  167. /// <param name="savePath"></param>
  168. /// <returns></returns>
  169. public static List<string> UploadFile(HttpFileCollectionBase fileList, string savePath = null)
  170. {
  171. UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
  172. List<string> result = new List<string>();
  173. string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
  174. string physicalPath = HttpContext.Current.Server.MapPath(filePath);
  175. string dayFolderName = DateTime.Today.ToString("yyyy-MM");
  176. string tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\") + dayFolderName + "\\";
  177. if (!string.IsNullOrEmpty(savePath))
  178. {
  179. filePath += "/" + savePath;
  180. physicalPath = HttpContext.Current.Server.MapPath(filePath);
  181. tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\");
  182. }
  183. else
  184. {
  185. filePath += "/" + dayFolderName;
  186. }
  187. if (!Directory.Exists(tagetPhysicalPath))
  188. {
  189. Directory.CreateDirectory(tagetPhysicalPath);
  190. }
  191. foreach (HttpPostedFile file in fileList)
  192. {
  193. var newFileName = Guid.NewGuid().ToString() + "." + Path.GetExtension(file.FileName);
  194. var webFileName = filePath + "/" + newFileName;
  195. var physicalFileName = tagetPhysicalPath + newFileName;
  196. file.SaveAs(physicalFileName);
  197. result.Add(urlHelper.Content(webFileName));
  198. }
  199. return result;
  200. }
  201. /// <summary>
  202. /// 文件上传并解压
  203. /// savePath是相对与web上传路径的子路径
  204. /// 如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
  205. /// </summary>
  206. /// <param name="file"></param>
  207. /// <param name="savePath"></param>
  208. /// <returns></returns>
  209. public static IList<string> UploadFileAndExtractFile(HttpPostedFileBase file, string savePath = null)
  210. {
  211. var physicalFileName = UploadFileInternal(file, savePath);
  212. if (physicalFileName == null) return new List<string>();
  213. var targetPhysicalFileName = physicalFileName.Replace(Path.GetExtension(physicalFileName), "");
  214. var result = ZIPHelper.ExtractZFile(physicalFileName, targetPhysicalFileName);
  215. //var filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
  216. UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
  217. result = result.Select(s => urlHelper.Content("~/" + s.Replace(HttpContext.Current.Server.MapPath("~/"), "").Replace("\\", "//"))).ToList();
  218. return result;
  219. }
  220. /// <summary>
  221. /// 文件上传并解压
  222. /// savePath是相对与web上传路径的子路径
  223. /// 如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
  224. /// </summary>
  225. /// <param name="file"></param>
  226. /// <param name="fileSourceWebPath"></param>
  227. /// <param name="errorSourceWebPath"></param>
  228. /// <param name="savePath"></param>
  229. /// <returns></returns>
  230. public static IList<string> UploadFileAndExtractFile(HttpPostedFileBase file, out string fileSourceWebPath,
  231. out string errorSourceWebPath, string savePath = null)
  232. {
  233. var physicalFileName = UploadFileInternal(file, out fileSourceWebPath, out errorSourceWebPath, savePath);
  234. if (physicalFileName == null) return new List<string>();
  235. var targetPhysicalFileName = physicalFileName.Replace(Path.GetExtension(physicalFileName), "");
  236. var result = ZIPHelper.ExtractZFile(physicalFileName, targetPhysicalFileName);
  237. //var filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
  238. UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
  239. result = result.Select(s => urlHelper.Content("~/" + s.Replace(HttpContext.Current.Server.MapPath("~/"), "").Replace("\\", "//"))).ToList();
  240. return result;
  241. }
  242. /// <summary>
  243. /// 删除File
  244. /// </summary>
  245. /// <param name="filePath"></param>
  246. public static void DeleteFile(string filePath)
  247. {
  248. DeleteFileInternal(filePath);
  249. }
  250. /// <summary>
  251. /// 批量下载文件并打包
  252. /// </summary>
  253. /// <param name="packageName">打包文件的文件名</param>
  254. /// <param name="fileNames">下载的临时文件的虚拟路径数组</param>
  255. /// <param name="remotePaths">远程文件地址数组</param>
  256. /// <remarks>fileNames和remotePaths的长度必须一致,并且同一索引的fileNames元素和remotePaths元素对应</remarks>
  257. /// <example>
  258. /// fileInfos[0].FileName = "文件1.txt";
  259. /// fileInfos[0].RemotePath = "http://www.google.com/html1.txt";
  260. /// fileInfos[1].FileName = "文件2.txt";
  261. /// fileInfos[1].RemotePath = "http://www.google.com/html2.txt";
  262. /// fileInfos[2].FileName = "文件3.txt";
  263. /// fileInfos[2].RemotePath = "http://www.google.com/html3.txt";
  264. ///
  265. /// packagePath = "c:\aa.rar";
  266. ///
  267. /// 执行结果:将http://www.google.com/html1.txt下载并保存为文件1.txt,
  268. /// http://www.google.com/html2.txt下载并保存为文件2.txt,
  269. /// http://www.google.com/html3.txt下载并保存为文件3.txt
  270. /// 然后将这三个文件打成压缩包,保存在c:\aa.rar中
  271. /// </example>
  272. public static Stream DownLoadFiles(string packageName, string downloadName, IList<RemoteFileInfo> fileInfos)
  273. {
  274. string rarTmpPathName = "RarTmp" + Guid.NewGuid().ToString();
  275. if (fileInfos.Count == 0)
  276. {
  277. throw new Exception("导出照片失败,找不到照片。");
  278. //return;
  279. }
  280. #region 下载文件
  281. string physicalPath = HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName);
  282. Directory.CreateDirectory(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName));
  283. //去重复
  284. var fileInfosDistinct = fileInfos.GroupBy(x => new { x.FileName, x.RemotePath }).Select(w => new { w.Key.FileName, w.Key.RemotePath });
  285. var downloadedFileInfo = fileInfosDistinct.Take(0).ToList();
  286. foreach (var fileInfo in fileInfosDistinct)
  287. {
  288. try
  289. {
  290. var localfilePath = Path.GetDirectoryName(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName + "/" + fileInfo.FileName));
  291. if (!Directory.Exists(localfilePath))
  292. {
  293. Directory.CreateDirectory(localfilePath);
  294. }
  295. FileManager.DownloadFile(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName + "/" + fileInfo.FileName, fileInfo.RemotePath);
  296. downloadedFileInfo.Add(fileInfo);
  297. }
  298. catch (Exception ex)
  299. {
  300. string e = ex.ToString();
  301. continue;
  302. }
  303. }
  304. if (downloadedFileInfo.Count == 0)
  305. {
  306. throw new Exception("所有的下载文件都不存在,无法下载。");
  307. }
  308. #endregion
  309. System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
  310. #region 打包
  311. string packageFullPath = HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + packageName);
  312. string tmpFilePath = HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName);
  313. using (ZipFile zipNew = new ZipFile())
  314. {
  315. zipNew.AlternateEncoding = Encoding.UTF8;
  316. zipNew.AlternateEncodingUsage = ZipOption.AsNecessary;
  317. //去重复,压缩时若有重复文件会报“已添加了具有相同键的项”错误
  318. foreach (var fileInfo in downloadedFileInfo)
  319. {
  320. string UrlList = tmpFilePath + @"\" + fileInfo.FileName;
  321. zipNew.AddFile(UrlList, @"\" + Path.GetDirectoryName(fileInfo.FileName));
  322. }
  323. zipNew.Save(packageFullPath + ".zip");
  324. }
  325. Directory.Delete(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName), true);
  326. #endregion
  327. #region 弹出下载窗口
  328. System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
  329. response.Clear();
  330. response.WriteFile(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + packageName + ".zip"));
  331. string httpHeader = "attachment;filename=" + server.UrlEncode(downloadName) + ".zip";
  332. response.AppendHeader("Content-Disposition", httpHeader);
  333. response.Flush();
  334. System.IO.File.Delete(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + packageName + ".zip"));//删除临时文件
  335. //response.End();
  336. return response.OutputStream;
  337. #endregion
  338. }
  339. }
  340. }