using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.IO; using System.Collections.Specialized; using zhjy.BLL.w_disk; using zhjy.Model; using ICSharpCode.SharpZipLib.Zip; using Common.ToolsCommon; using zhjy.BLL.w_data; namespace Web.yunpan { public static class DiskHelp { /// <summary> /// 公共云盘根目录 /// </summary> public static readonly string publicDiskBasePath; /// <summary> /// 个人云盘根目录 /// </summary> public static readonly string privateDiskBasePath; static DiskHelp() { //publicDiskBasePath = ConfigurationManager.AppSettings["publicDiskBasePath"]; //privateDiskBasePath = ConfigurationManager.AppSettings["privateDiskBasePath"]; if (HttpContext.Current != null) { publicDiskBasePath = HttpContext.Current.Server.MapPath("~/CloudDisk/PublicDoc"); privateDiskBasePath = HttpContext.Current.Server.MapPath("~/CloudDisk/PrivateDoc"); } else { publicDiskBasePath = System.Web.Hosting.HostingEnvironment.MapPath("~/CloudDisk/PublicDoc"); privateDiskBasePath = System.Web.Hosting.HostingEnvironment.MapPath("~/CloudDisk/PrivateDoc"); } } /// <summary> /// 初始化生成文件夹 /// </summary> /// <returns></returns> public static bool InitFolderList() { string msg = string.Empty; int userId = GetLoginUserId(); IList<string> folderNameList = new List<string> { "", "", "", "", "" }; string userPriverBasePath = Path.Combine(privateDiskBasePath, userId.ToString()); if (!Directory.Exists(userPriverBasePath))//路径不存在初始化文件夹 { w_disk_folderBLL folderBLL = new w_disk_folderBLL(); foreach (var item in folderNameList) { string folderPath = string.Empty; bool isSuc = CreateFolder(item, userId, ref msg, ref folderPath); if (!isSuc) { return false; } folderBLL.Add(new w_disk_folder { folderName = item, url = ToRelativePath(folderPath), createrId = GetLoginUserId(), createrName = GetLoginUserName(), creatDate = DateTime.Now }); } } return true; } /// <summary> /// 创建 /// </summary> /// <param name="folderName"></param> /// <param name="userId"></param> /// <param name="msg"></param> /// <returns></returns> public static bool CreateFolder(string folderName, int userId, ref string msg, ref string path) { if (string.IsNullOrWhiteSpace(folderName)) { msg = "文件夹名不能为空"; return false; } path = Path.Combine(privateDiskBasePath, userId.ToString(), folderName); if (Directory.Exists(path)) { msg = "当前文件夹已存在"; return false; } Directory.CreateDirectory(path); return true; } public static bool RenameFolder(string oldFolderName, string newFolderName, int userId, ref string msg, ref string newPath) { if (string.IsNullOrWhiteSpace(oldFolderName) || string.IsNullOrWhiteSpace(newFolderName)) { msg = "文件夹名不能为空"; return false; } if (oldFolderName == newFolderName) { msg = "文件夹命名重复"; return false; } string path = Path.Combine(privateDiskBasePath, userId.ToString(), oldFolderName); if (!Directory.Exists(path)) { msg = "当前文件夹不存在"; return false; } newPath = Path.Combine(privateDiskBasePath, userId.ToString(), newFolderName); Directory.Move(path, newPath); return true; } public static bool DeleteFolder(string folderName, int userId, ref string msg) { if (string.IsNullOrWhiteSpace(folderName)) { msg = "文件夹名不能为空"; return false; } string path = Path.Combine(privateDiskBasePath, userId.ToString(), folderName); if (!Directory.Exists(path)) { msg = "当前文件夹不存在"; return false; } DirectoryInfo dir = new DirectoryInfo(path); int fileCount = dir.GetFiles().Length; if (fileCount != 0) { msg = "当前文件夹不为空,请先删除文件夹下的文件"; return false; } dir.Delete(); return true; } public static bool UploadFile(string folderName, int userId, ref w_disk_file diskFile, ref string msg) { if (HttpContext.Current.Request.Files.Count == 0 || string.IsNullOrWhiteSpace(HttpContext.Current.Request.Files[0].FileName)) { msg = "当前没有文件上传"; return false; } HttpPostedFile file = HttpContext.Current.Request.Files[0]; string fileName = Path.GetFileName(file.FileName); if (!IsFileNameValid(fileName)) { msg = "请勿在文件名中包含\\ / : * ? \" < > |等字符,请重新输入有效文件名!"; return false; } if (diskFile.typeId == "2" && !IsVideo(file)) { msg = "请上传视频文件"; return false; } if (!IsAllowedExtension(file)) { msg = "当前类型的文件不允许上传!"; return false; } string path = string.Empty; if (diskFile.isPublic) { path = Path.Combine(publicDiskBasePath, folderName); } else { path = Path.Combine(privateDiskBasePath, userId.ToString(), folderName); } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = Path.Combine(path, RenameFileName(fileName)); if (File.Exists(path)) { msg = fileName + "文件已存在!"; return false; } file.SaveAs(path); if (IsVideo(file) && Path.GetExtension(fileName) != ".mp4") { //将视频转码加入队列 DiskTransCodQuenu.Add(path); } diskFile.url = ToRelativePath(path); diskFile.fileName = fileName; diskFile.createrId = userId; diskFile.creatDate = DateTime.Now; diskFile.viewCount = 0; diskFile.fileSize = GetMB(file.ContentLength); diskFile.format = Path.GetExtension(fileName).Replace(".", ""); return true; } public static bool SimpleUploadFile(string uploadpath, bool isAbsolutePath, ref string msg, ref string uploadinfo) { if (HttpContext.Current.Request.Files.Count == 0) { msg = "当前没有文件上传"; return false; } var files = HttpContext.Current.Request.Files; for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++) { string fileName = Path.GetFileName(files[0].FileName); if (!IsFileNameValid(fileName)) { msg = "请勿在文件名中包含\\ / : * ? \" < > |等字符,请重新输入有效文件名!"; return false; } if (!IsAllowedExtension(files[0])) { msg = "当前类型的文件不允许上传!"; return false; } if (!Directory.Exists(uploadpath)) { Directory.CreateDirectory(uploadpath); } uploadpath = Path.Combine(uploadpath, fileName); if (File.Exists(uploadpath)) { msg = fileName + "文件已存在!"; return false; } files[0].SaveAs(uploadpath); if (!isAbsolutePath) { uploadpath = ToRelativePath(uploadpath); } uploadinfo = "{\"paht\":\"" + uploadpath.Replace("\\", "\\\\") + "\",\"fileName\":\"" + fileName + "\"}"; } return true; } /// <summary> /// 复制到公共云盘 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string CopyToPublicCloud(string url) { url = ToPhysicsPath(url); string fileName = Path.GetFileName(url); string toPath = Path.Combine(publicDiskBasePath, DateTime.Now.ToString("yyyy-MM-dd")); if (!System.IO.Directory.Exists(toPath)) { System.IO.Directory.CreateDirectory(toPath); } toPath = Path.Combine(toPath, fileName); File.Copy(url, toPath, false); string extension = Path.GetExtension(toPath); if (IsVideo(extension.Replace(".", "")) && extension != ".mp4") { //将视频转码加入队列 DiskTransCodQuenu.Add(toPath); } return ToRelativePath(toPath); } /// <summary> /// 文件下载 /// </summary> /// <param name="fileName">文件名</param> /// <param name="url">文件地址</param> public static void DownFile(string fileName, string url) { try { var response = HttpContext.Current.Response; response.ContentType = "application/x-zip-compressed"; response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); response.TransmitFile(url); } catch (Exception) { } } /// <summary> /// 批量下载 /// </summary> /// <param name="urlList">文件路径List</param> public static void BatchDownFile(List<string> urlList, int userId) { /*删除之前的临时文件*/ string path = Path.Combine(privateDiskBasePath, userId.ToString(), "tempZip"); DirectoryInfo dirInfo = new DirectoryInfo(path); if (dirInfo.Exists) { dirInfo.Delete(true); } dirInfo.Create(); string fileName = Path.Combine(path, "打包文件.zip"); using (ZipFile zip = ZipFile.Create(fileName)) { zip.BeginUpdate(); zip.SetComment("压缩包"); foreach (var item in urlList) { string phtPath = ToPhysicsPath(item); if (File.Exists(phtPath))//判断文件是否存在 { StaticDiskDataSource dataSource = new StaticDiskDataSource(phtPath); string[] fileNameSplit = phtPath.Split('\\'); zip.Add(dataSource, fileNameSplit[fileNameSplit.Length - 1]); } } zip.CommitUpdate(); } DownFile("打包文件.zip", fileName); } public static void DelFile(string url) { if (!string.IsNullOrWhiteSpace(url)) { url = ToPhysicsPath(url); if (File.Exists(url)) { File.Delete(url); } } } public static bool FileIsExist(string url) { if (!string.IsNullOrWhiteSpace(url)) { url = ToPhysicsPath(url); if (File.Exists(url)) { return true; } } return false; } public static string MoveFile(string fromUrl, string toFolderPath) { toFolderPath = ToPhysicsPath(toFolderPath); fromUrl = ToPhysicsPath(fromUrl); string toPath = Path.Combine(toFolderPath, Path.GetFileName(fromUrl)); File.Move(fromUrl, toPath); string extension = Path.GetExtension(toPath); if (IsVideo(extension.Replace(".", "")) && extension != ".mp4") { //将视频转码加入队列 DiskTransCodQuenu.Add(toPath); } return ToRelativePath(toPath); } /// <summary> /// 文件上传 /// </summary> /// <param name="userId"></param> /// <param name="diskFile"></param> /// <param name="folderName"></param> /// <param name="msg"></param> /// <returns></returns> public static int Upload(int userId, w_disk_file diskFile, string folderName, ref string msg) { int fileId = 0; bool isSuc = UploadFile(folderName, userId, ref diskFile, ref msg); if (isSuc) { w_disk_fileBLL bll = new w_disk_fileBLL(); string userName = GetLoginUserName(); if (!diskFile.isPublic) { diskFile.ownUserId = userId; diskFile.author = userName; } diskFile.createrName = userName; fileId = bll.Add(diskFile); } return fileId; } private static string RenameFileName(string fileName) { int userId = GetLoginUserId(); w_data_userInfoBLL userBLL = new w_data_userInfoBLL(); w_data_userInfo userInfo = userBLL.GetModel(userId); string extension = Path.GetExtension(fileName); Random rd = new Random(); return string.Format("{0}{1}{2}{3}{4}", DateTime.Now.ToString("yyyy"), userInfo.userNumber, DateTime.Now.ToString("MMddHHmmss"), rd.Next(1000, 9999), extension); } private static bool IsFileNameValid(string name) { bool isFilename = true; string[] errorStr = new string[] { "/", "\\", ":", ",", "*", "?", "\"", "<", ">", "|" }; int portCount = name.Count(c => c == '.'); if (portCount > 1)//文件名不能出现两个. { isFilename = false; } if (string.IsNullOrEmpty(name)) { isFilename = false; } else { for (int i = 0; i < errorStr.Length; i++) { if (name.Contains(errorStr[i])) { isFilename = false; break; } } } return isFilename; } private static bool IsAllowedExtension(HttpPostedFile file) { return true; } private static bool IsVideo(HttpPostedFile file) { return IsVideo(Path.GetExtension(file.FileName).Replace(".", "")); } /// <summary> /// 是否是音频文件 /// </summary> /// <param name="file"></param> /// <returns></returns> private static bool IsAudio(HttpPostedFile file) { bool isAudio = false; IList<string> formateList = new List<string> { ".wav",".mp3 ",".rma",".ra",".wma",".asf",".mid",".midi",".rmi",".xmi",".ogg" ,".vqf",".tvq",".mod",".ape",".aiff",".au" }; string formate = Path.GetExtension(file.FileName).ToLower(); if (formateList.Contains(formate)) { isAudio = true; } return isAudio; } public static bool IsVideo(string formate) { bool isVideo = false; IList<string> formateList = new List<string> { "avi","flv","mpg","mpeg","mpe","m1v","m2v","mpv2","mp2v","dat","ts","tp","tpr","pva","pss","mp4","m4v", "m4p","m4b","3gp","3gpp","3g2","3gp2","ogg","mov","qt","amr","rm","ram","rmvb","rpm"}; if (formateList.Contains(formate)) { isVideo = true; } return isVideo; } /// <summary> /// 将B转换为MB /// </summary> /// <param name="b"></param> /// <returns></returns> private static decimal GetMB(long b) { decimal size = (decimal)b; for (int i = 0; i < 2; i++) { size /= 1024; } return size; } public static int GetLoginUserId() { var userId = Utils.GetCookie("userId"); return userId != "" ? Convert.ToInt32(userId) : 0; } public static string GetLoginUserName() { string loginUserName = Utils.GetCookie("userName"); return loginUserName; } /// <summary> /// 转换成相对路径 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string ToRelativePath(string url) { if (url.StartsWith("/") || url.StartsWith("~/")) { return url; } string tmpRootDir = HttpContext.Current.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录 string relativeUrl = string.Empty; if (url.Contains(tmpRootDir)) { relativeUrl = url.Replace(tmpRootDir, ""); //转换成相对路径 relativeUrl = relativeUrl.Replace(@"\", @"/"); } return "/" + relativeUrl; } /// <summary> /// 转成物理路径 /// </summary> /// <param name="url"></param> /// <returns></returns> public static string ToPhysicsPath(string url) { if (url.StartsWith("/") || url.StartsWith("~/")) { if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(url); } else { return System.Web.Hosting.HostingEnvironment.MapPath(url); } } return url; } /// <summary> /// 转换成MP4格式 /// </summary> /// <param name="fromFilePath"></param> /// <returns></returns> public static string ToMp4(string fromFilePath) { string ffmpeg = Path.Combine(System.Web.HttpRuntime.AppDomainAppPath, "ffmpeg\\bin\\ffmpeg.exe");//ffmpeg执行文件的路径 int lastIndexPort = fromFilePath.LastIndexOf("."); string toPathFileName = fromFilePath.Substring(0, lastIndexPort) + ".mp4"; if ((!System.IO.File.Exists(ffmpeg))) { return string.Empty; ; } //转mp4格式 string Command = " -i \"" + fromFilePath + "\" -c:v libx264 -strict -2 \"" + toPathFileName + "\""; using (System.Diagnostics.Process p = new System.Diagnostics.Process()) { p.StartInfo.FileName = ffmpeg; p.StartInfo.Arguments = Command; //p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/temp/"); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false; p.Start(); p.BeginErrorReadLine(); p.WaitForExit(); p.Dispose(); return toPathFileName; } } } }