123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Web;
- using System.IO;
- using System.Web.UI;
- using System.Web.Mvc;
- using Bowin.Common;
- using Ionic.Zip;
- using Bowin.Common.Log;
- namespace EMIS.Utility
- {
- public class FileUploadHelper
- {
- public class RemoteFileInfo
- {
- public string FileName { get; set; }
- public string RemotePath { get; set; }
- }
- public static string GetFileUploadSessionName(Guid formID)
- {
- return Const.UPLOAD_SESSION_NAME + "_" + formID.ToString();
- }
- private const long BUFFER_SIZE = 4096;
- /// <summary>
- /// savePath是相对与web上传路径的子路径,如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
- /// </summary>
- /// <param name="fileList"></param>
- /// <param name="savePath"></param>
- /// <returns></returns>
- public static List<string> UploadFile(HttpFileCollectionBase fileList, string savePath = null)
- {
- UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
- List<string> result = new List<string>();
- string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
- string physicalPath = HttpContext.Current.Server.MapPath(filePath);
- string dayFolderName = DateTime.Today.ToString("yyyy-MM");
- string tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\") + dayFolderName + "\\";
- if (!string.IsNullOrEmpty(savePath))
- {
- filePath += "/" + savePath;
- physicalPath = HttpContext.Current.Server.MapPath(filePath);
- tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\");
- }
- else
- {
- filePath += "/" + dayFolderName;
- }
- if (!Directory.Exists(tagetPhysicalPath))
- {
- Directory.CreateDirectory(tagetPhysicalPath);
- }
- foreach (HttpPostedFile file in fileList)
- {
- var newFileName = Guid.NewGuid().ToString() + "." + Path.GetExtension(file.FileName);
- var webFileName = filePath + "/" + newFileName;
- var physicalFileName = tagetPhysicalPath + newFileName;
- file.SaveAs(physicalFileName);
- result.Add(urlHelper.Content(webFileName));
- }
- return result;
- }
- /// <summary>
- /// savePath是相对与web上传路径的子路径,如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
- /// </summary>
- /// <param name="file"></param>
- /// <param name="savePath"></param>
- /// <returns></returns>
- public static string UploadFile(HttpPostedFileBase file, string savePath = null)
- {
- if (file == null || string.IsNullOrEmpty(file.FileName)) return null;
- UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
- string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
- string dayFolderName = DateTime.Today.ToString("yyyy-MM");
- var physicalFileName = UploadFileInternal(file, savePath);
- if (!string.IsNullOrEmpty(savePath))
- {
- filePath += "/" + savePath;
- }
- else
- {
- filePath += "/" + dayFolderName;
- }
- var webFileName = filePath + "/" + Path.GetFileName(physicalFileName);
- return urlHelper.Content(webFileName);
- }
- public static string UploadFile(MemoryStream file, string extName, string savePath = null)
- {
- if (file == null || file.Length == 0) return null;
- UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
- string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
- string dayFolderName = DateTime.Today.ToString("yyyy-MM");
- var physicalFileName = UploadFileInternal(file, extName, savePath);
- if (!string.IsNullOrEmpty(savePath))
- {
- filePath += "/" + savePath;
- }
- else
- {
- filePath += "/" + dayFolderName;
- }
- var webFileName = filePath + "/" + Path.GetFileName(physicalFileName);
- return urlHelper.Content(webFileName);
- }
- public static void DeleteFile(string filePath)
- {
- DeleteFileInternal(filePath);
- }
- /// <summary>
- /// savePath是相对与web上传路径的子路径,如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
- /// </summary>
- /// <param name="file"></param>
- /// <param name="savePath"></param>
- /// <returns></returns>
- public static IList<string> UploadFileAndExtractFile(HttpPostedFileBase file, string savePath = null)
- {
- var physicalFileName = UploadFileInternal(file, savePath);
- if (physicalFileName == null) return new List<string>();
- var targetPhysicalFileName = physicalFileName.Replace(Path.GetExtension(physicalFileName), "");
- var result = ZIPHelper.SevenZip_ExtractStream(physicalFileName, targetPhysicalFileName);
- //var filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
- UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
- result = result.Select(s => urlHelper.Content("~/" + s.Replace(HttpContext.Current.Server.MapPath("~/"), "").Replace("\\", "//"))).ToList();
- return result;
- }
- /// <summary>
- /// savePath是相对与web上传路径的子路径,如:web上传路径为~/Content/DownFile,savePath为SOC/2018-201901,则实际上传的路径为~/Content/DownFile/SOC/2018-201901
- /// </summary>
- /// <param name="file"></param>
- /// <param name="savePath"></param>
- /// <returns></returns>
- public static string UploadFileInternal(HttpPostedFileBase file, string savePath = null)
- {
- LogHelper.WriteLog(LogType.ServiceLog, "----进入UploadFileInternal方法-----");
- if (file == null || string.IsNullOrEmpty(file.FileName)) return null;
- UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
- string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
- string physicalPath = HttpContext.Current.Server.MapPath(filePath);
- string dayFolderName = DateTime.Today.ToString("yyyy-MM");
- string tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\") + dayFolderName + "\\";
- if (!string.IsNullOrEmpty(savePath))
- {
- filePath += "/" + savePath;
- physicalPath = HttpContext.Current.Server.MapPath(filePath);
- tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\");
- }
- if (!Directory.Exists(tagetPhysicalPath))
- {
- Directory.CreateDirectory(tagetPhysicalPath);
- }
- var newFileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
- var physicalFileName = tagetPhysicalPath + newFileName;
- file.SaveAs(physicalFileName);
- return physicalFileName;
- }
- public static string UploadFileInternal(MemoryStream file, string extName, string savePath = null)
- {
- if (file == null || file.Length == 0) return null;
- UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
- string filePath = Const.LOCAL_SETTING_UPLOAD_FILEPATH;
- string physicalPath = HttpContext.Current.Server.MapPath(filePath);
- string dayFolderName = DateTime.Today.ToString("yyyy-MM");
- string tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\") + dayFolderName + "\\";
- if (!string.IsNullOrEmpty(savePath))
- {
- filePath += "/" + savePath;
- physicalPath = HttpContext.Current.Server.MapPath(filePath);
- tagetPhysicalPath = (physicalPath.EndsWith("\\") ? physicalPath : physicalPath + "\\");
- }
- if (!Directory.Exists(tagetPhysicalPath))
- {
- Directory.CreateDirectory(tagetPhysicalPath);
- }
- var newFileName = Guid.NewGuid().ToString() + extName;
- var physicalFileName = tagetPhysicalPath + newFileName;
- FileStream fs = File.Create(physicalFileName);
- var fileData = file.GetBuffer();
- fs.Write(fileData, 0, fileData.Length);
- fs.Flush();
- fs.Close();
- return physicalFileName;
- }
- public static void DeleteFileInternal(string filePath)
- {
- string fullPath = HttpContext.Current.Server.MapPath("~" + filePath);
- File.Delete(fullPath);
- }
- /// <summary>
- /// 批量下载文件并打包
- /// </summary>
- /// <param name="packageName">打包文件的文件名</param>
- /// <param name="fileNames">下载的临时文件的虚拟路径数组</param>
- /// <param name="remotePaths">远程文件地址数组</param>
- /// <remarks>fileNames和remotePaths的长度必须一致,并且同一索引的fileNames元素和remotePaths元素对应</remarks>
- /// <example>
- /// fileInfos[0].FileName = "文件1.txt";
- /// fileInfos[0].RemotePath = "http://www.google.com/html1.txt";
- /// fileInfos[1].FileName = "文件2.txt";
- /// fileInfos[1].RemotePath = "http://www.google.com/html2.txt";
- /// fileInfos[2].FileName = "文件3.txt";
- /// fileInfos[2].RemotePath = "http://www.google.com/html3.txt";
- ///
- /// packagePath = "c:\aa.rar";
- ///
- /// 执行结果:将http://www.google.com/html1.txt下载并保存为文件1.txt,
- /// http://www.google.com/html2.txt下载并保存为文件2.txt,
- /// http://www.google.com/html3.txt下载并保存为文件3.txt
- /// 然后将这三个文件打成压缩包,保存在c:\aa.rar中
- /// </example>
- public static Stream DownLoadFiles(string packageName, string downloadName, IList<RemoteFileInfo> fileInfos)
- {
- string rarTmpPathName = "RarTmp" + Guid.NewGuid().ToString();
- if (fileInfos.Count == 0)
- {
- throw new Exception("导出相片失败,找不到相片");
- //return;
- }
- #region 下载文件
- string physicalPath = HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName);
- Directory.CreateDirectory(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName));
- //去重复
- var fileInfosDistinct = fileInfos.GroupBy(x => new { x.FileName, x.RemotePath }).Select(w => new { w.Key.FileName, w.Key.RemotePath }).ToList();
- var downloadedFileInfo = fileInfosDistinct.Take(0).ToList();
- foreach (var fileInfo in fileInfosDistinct)
- {
- try
- {
- var localfilePath = Path.GetDirectoryName(
- HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName + "/" + fileInfo.FileName)
- );
- if (!Directory.Exists(localfilePath))
- {
- Directory.CreateDirectory(localfilePath);
- }
- FileManager.DownloadFile(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName + "/" + fileInfo.FileName, fileInfo.RemotePath);
- downloadedFileInfo.Add(fileInfo);
- }
- catch (Exception ex)
- {
- string e = ex.ToString();
- continue;
- }
- }
- if (downloadedFileInfo.Count == 0)
- {
- throw new Exception("所有的下载文件都不存在,无法下载。");
- }
- #endregion
- System.Web.HttpServerUtility server = System.Web.HttpContext.Current.Server;
- #region 打包
- string packageFullPath = HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + packageName);
- string tmpFilePath = HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName);
- using (ZipFile zipNew = new ZipFile())
- {
- zipNew.AlternateEncoding = Encoding.UTF8;
- zipNew.AlternateEncodingUsage = ZipOption.AsNecessary;
- //去重复,压缩时若有重复文件会报“已添加了具有相同键的项”错误
- foreach (var fileInfo in downloadedFileInfo)
- {
- string UrlList = tmpFilePath + @"\" + fileInfo.FileName;
- zipNew.AddFile(UrlList, @"\" + Path.GetDirectoryName(fileInfo.FileName));
- }
- zipNew.Save(packageFullPath + ".zip");
- }
- Directory.Delete(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + rarTmpPathName), true);
- #endregion
- #region 弹出下载窗口
- System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
- response.Clear();
- response.WriteFile(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + packageName + ".zip"));
- string httpHeader = "attachment;filename=" + server.UrlEncode(downloadName) + ".zip";
- response.AppendHeader("Content-Disposition", httpHeader);
- response.Flush();
- System.IO.File.Delete(HttpContext.Current.Server.MapPath(Const.LOCAL_SETTING_UPLOAD_FILEPATH + "/" + packageName + ".zip"));//删除临时文件
- //response.End();
- return response.OutputStream;
- #endregion
- }
- }
- }
|