123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- 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
- {
- /// <summary>
- /// 表示文件是否已上传成功。
- /// </summary>
- // ReSharper disable once InconsistentNaming
- public bool Success;
- /// <summary>
- /// 自定义的附加消息。
- /// </summary>
- // ReSharper disable once InconsistentNaming
- public string Msg;
- /// <summary>
- /// 表示所有文件的保存地址,该变量为一个数组。
- /// </summary>
- // ReSharper disable once InconsistentNaming
- public ArrayList FileUrls;
- public ArrayList VirtualPathUrls;
- }
- }
|