using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace SysBaseLibs { public class UploadFileHelper { public static UploadFileHelper Instance { get; } = new UploadFileHelper(); public UploadResult UploadFiles(string filePath, string fileType, HttpRequestBase request, HttpServerUtilityBase server) { UploadResult result = new UploadResult { FileUrls = new ArrayList(), Success = false, Msg = "Failure!", VirtualPathUrls = new ArrayList(), }; //遍历所有文件域 foreach (string fieldName in request.Files.AllKeys) { HttpPostedFileBase file = request.Files.Get(fieldName); string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); filePath += ymd + "/"; string fileName = DateTime.Now.ToString("yyyyMMddhhmmss_ffff"); string urlPath = $"{filePath}{fileName}.{fileType}"; string virtualPath = server.MapPath(urlPath); try { if (!Directory.Exists(server.MapPath(filePath))) Directory.CreateDirectory(server.MapPath(filePath)); file?.SaveAs(virtualPath); result.FileUrls.Add(urlPath); result.VirtualPathUrls.Add(virtualPath); result.Success = true; result.Msg = "Success!"; } catch (Exception e) { result.Msg = e.Message; return result; } } return result; } public UploadResult UploadFiles2(string filePath, HttpPostedFileBase requestFile, HttpServerUtilityBase server) { UploadResult result = new UploadResult { FileUrls = new ArrayList(), Success = false, Msg = "Failure!" }; //遍历所有文件域 string urlPath = $"{filePath}"; string virtualPath = server.MapPath(urlPath); try { if (File.Exists(virtualPath)) File.Delete(virtualPath); requestFile?.SaveAs(virtualPath); result.FileUrls.Add(urlPath); result.VirtualPathUrls.Add(virtualPath); result.Success = true; result.Msg = "Success!"; } catch (Exception e) { result.Msg = e.Message; return result; } return result; } } public class UploadResult { /// /// 表示文件是否已上传成功。 /// // ReSharper disable once InconsistentNaming public bool Success; /// /// 自定义的附加消息。 /// // ReSharper disable once InconsistentNaming public string Msg; /// /// 表示所有文件的保存地址,该变量为一个数组。 /// // ReSharper disable once InconsistentNaming public ArrayList FileUrls; public ArrayList VirtualPathUrls; } }