ASP.NET實現的簡單易用檔案上傳類_實用技巧

來源:互聯網
上載者:User

調用方法:

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  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.