ASP.NET 에서 구현 되 는 간단 한 파일 업로드 클래스

호출 방법:

UploadFile uf = new UploadFile();
 
/*    */
uf.SetIsUseOldFileName(true);//                  (  :true),true     ,false        
uf.SetFileDirectory(Server.MapPath("/file/temp3/"));//      (  :/upload)
uf.SetFileType("*");//         ,     ,      ! *     (   : .pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif ) 
uf.SetIsRenameSameFile(false);//       ?
 
 
//          
var message = uf.Save(Request.Files["Fileupload1"]); // “/file/temp3/2015/4/xx.jpg”
 
//          
var message2 = uf.Save(Request.Files["Fileupload1"], "001" /*  */); //  “/file/temp3/001/xx.jpg”
 
 
//    
var isError = message.Error;//        
var webPath = message.WebFilePath;//  web  
var msg = message.Message;//      
var filePath = message.FilePath;//      
var isSuccess = message.Error == false;

코드:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
 
 
namespace SyntacticSugar
{
  /// <summary>
  /// **   :       (          )
  /// **     :2015-5-27
  /// **     :-
  /// **   :sunkaixuan
  /// </summary>
  public class UploadFile
  {
 
    private ParamsModel Params;
    public UploadFile()
    {
      Params = new ParamsModel()
      {
        FileDirectory = "/upload",
        FileType = ".pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif",
        MaxSizeM = 10,
        PathSaveType = PathSaveType.dateTimeNow,
        IsRenameSameFile=true
      };
    }
 
    /// <summary>
    ///       (  :/upload)
    /// </summary>
    public void SetFileDirectory(string fileDirectory)
    {
      if (fileDirectory == null)
      {
        throw new ArgumentNullException("fileDirectory");
      }
 
      var isMapPath = Regex.IsMatch(fileDirectory, @"[a-z]\:\\", RegexOptions.IgnoreCase);
      if (isMapPath)
      {
        fileDirectory = GetRelativePath(fileDirectory);
      }
      Params.FileDirectory = fileDirectory;
    }
 
  
    /// <summary>
    ///                   (  :true)
    /// </summary>
    /// <param name="isUseOldFileName">true     ,false        </param>
    public void SetIsUseOldFileName(bool isUseOldFileName)
    {
      Params.IsUseOldFileName = isUseOldFileName;
    }
 
    /// <summary>
    ///          ,     ,      ! *     (   : .pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif ) 
    /// </summary>
    public void SetFileType(string fileType)
    {
      Params.FileType = fileType;
    }
    /// <summary>
    ///         (  :M)
    /// </summary>
    public void SetMaxSizeM(double maxSizeM)
    {
      Params.MaxSizeM = maxSizeM;
    }
    /// <summary>
    ///        ?
    /// </summary>
    /// <param name="isRenameSameFile">true:   ,false  </param>
    public void SetIsRenameSameFile(bool isRenameSameFile)
    {
      Params.IsRenameSameFile = isRenameSameFile;
    }
 
 
    /// <summary>
    ///       
    /// </summary>
    /// <param name="postFile">HttpPostedFile</param>
    /// <returns></returns>
    public ResponseMessage Save(HttpPostedFile postFile)
    {
      return CommonSave(postFile);
    }
 
 
 
    /// <summary>
    ///       ,          
    /// </summary>
    /// <param name="postFile">HttpPostedFile</param>
    /// <param name="number">  </param>
    /// <returns></returns>
    public ResponseMessage Save(HttpPostedFile postFile, string number)
    {
 
      Params.PathSaveType = PathSaveType.code;
      _Number = number;
      return CommonSave(postFile);
    }
 
 
    /// <summary>
    ///       ,  HttpPostedFile
    /// </summary>
    /// <param name="postFile">HttpPostedFile</param>
    /// <param name="isRenameSameFile">  true          ,false      </param>
    /// <param name="fileName">     </param>
    /// <returns></returns>
    private ResponseMessage CommonSave(HttpPostedFile postFile)
    {
 
      ResponseMessage reval = new ResponseMessage();
      try
      {
        if (postFile == null || postFile.ContentLength == 0)
        {
          TryError(reval, "    !");
          return reval;
        }
 
        //   
        string fileName = Params.IsUseOldFileName ? postFile.FileName : DateTime.Now.ToString("yyyyMMddhhmmssms") + Path.GetExtension(postFile.FileName);
 
        //    
        this.CheckingType(reval, postFile.FileName);
        //    
        this.CheckSize(reval, postFile);
 
        if (reval.Error) return reval;
 
 
        string webDir = string.Empty;
        //       
        var directory = this.GetDirectory(ref webDir);
        var filePath = directory + fileName;
        if (System.IO.File.Exists(filePath))
        {
          if (Params.IsRenameSameFile)
          {
            filePath = directory + DateTime.Now.ToString("yyyyMMddhhssms") + "-" + fileName;
          }
          else
          {
            System.IO.File.Delete(filePath);
          }
        }
        //     
        postFile.SaveAs(filePath);
        reval.FilePath = filePath;
        reval.FilePath = webDir + fileName;
        reval.FileName = fileName;
        reval.WebFilePath = webDir + fileName;
        return reval;
      }
      catch (Exception ex)
      {
        TryError(reval, ex.Message);
        return reval;
      }
    }
 
    private void CheckSize(ResponseMessage message, HttpPostedFile PostFile)
    {
      if (PostFile.ContentLength / 1024.0 / 1024.0 > Params.MaxSizeM)
      {
        TryError(message, string.Format("         ,    {0}M!", Params.MaxSizeM));
      }
    }
    /// <summary>
    ///             
    /// </summary>
    /// <param name="fileDirectory"></param>
    /// <param name="sever"></param>
    /// <returns></returns>
    private static string GetRelativePath(string fileDirectory)
    {
      var sever = HttpContext.Current.Server;
      fileDirectory = "/" + fileDirectory.Replace(sever.MapPath("~/"), "").TrimStart('/').Replace('\\', '/');
      return fileDirectory;
    }
 
    /// <summary>
    ///     
    /// </summary>
    /// <returns></returns>
    private string GetDirectory(ref string webDir)
    {
      var sever = HttpContext.Current.Server;
      //     
      string directory = Params.FileDirectory;
 
      //     
      string childDirectory = DateTime.Now.ToString("yyyy-MM/dd");
      if (Params.PathSaveType == PathSaveType.code)
      {
        childDirectory = _Number;
      }
      webDir = directory.TrimEnd('/') + "/" + childDirectory + '/';
      string dir = sever.MapPath(webDir);
      //     
      if (Directory.Exists(dir) == false)
        Directory.CreateDirectory(dir);
      return dir;
    }
 
    /// <summary>
    ///       )
    /// </summary>
    /// <param name="fileName"></param>
    private void CheckingType(ResponseMessage message, string fileName)
    {
      if (Params.FileType != "*")
      {
        //             
        string[] typeList = Params.FileType.Split(',');
 
        //         (  )
        string type = Path.GetExtension(fileName).ToLowerInvariant(); ;
 
        //     
        if (typeList.Contains(type) == false)
          this.TryError(message, "      !");
      }
    }
 
    /// <summary>
    ///     
    /// </summary>
    /// <param name="Msg"></param>
    private void TryError(ResponseMessage message, string msg)
    {
      message.Error = true;
      message.Message = msg;
    }
 
    #region models
 
    private class ParamsModel
    {
      /// <summary>
      ///       
      /// </summary>
      public string FileDirectory { get; set; }
      /// <summary>
      ///          ,     ,      !
      /// </summary>
      public string FileType { get; set; }
      /// <summary>
      ///         
      /// </summary>
      public double MaxSizeM { get; set; }
      /// <summary>
      ///       
      /// </summary>
      public PathSaveType PathSaveType { get; set; }
      /// <summary>
      ///        ?
      /// </summary>
      public bool IsRenameSameFile { get; set; }
      /// <summary>
      ///          
      /// </summary>
      public bool IsUseOldFileName { get; set; }
    }
 
 
    /// <summary>
    ///       
    /// </summary>
    public enum PathSaveType
    {
      /// <summary>
      ///           
      /// </summary>
      dateTimeNow = 0,
      /// <summary>
      ///   ID           
      /// </summary>
      code = 1
 
    }
    private string _Number { get; set; }
 
    /// <summary>
    ///     
    /// </summary>
    public class ResponseMessage
    {
      /// <summary>
      ///     
      /// </summary>
      public bool Error { get; set; }
      /// <summary>
      ///   
      /// </summary>
      public string Message { get; set; }
      /// <summary>
      ///     
      /// </summary>
      public string FilePath { get; set; }
      /// <summary>
      ///     
      /// </summary>
      public string WebFilePath { get; set; }
      /// <summary>
      ///      
      /// </summary>
      public string FileName { get; set; }
 
    }
    #endregion
  }
}

좋은 웹페이지 즐겨찾기