星空网 > 软件开发 > ASP.net

ASP.NET 文件上传类 简单好用

调用:

 UploadFile uf = new UploadFile();    //参数设置    //uf.SetFilePath=""    设置保存路径,默认为upload    //uf.SetFileType=".exe"  设置允许的后缀格式,默认为.pdf,.xls,.xlsx,.doc,.docx,.txt     //uf.SetMaxSizeM=100    设置最大上传大小 默认10M    //执行保存    uf.Save("file" /*input file 的 name */ , true); //true会自动处理同名文件,false则覆盖同名文件    //返回信息    var isError = uf.GetError;//判段是否上传成功    var webPath = uf.GetWebFilePath;//返回web路径    var response = uf.GetMessage;//返回上传信息    var filePath = uf.GetFilePath;//反回文件路径

 

 

 

代码:

 

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Security.Cryptography;using System.Web;namespace SyntacticSugar{  /// <summary>  /// ** 描述:单文件上传类 (暂时不支持多文件上传  /// ** 创始时间:2015-5-27  /// ** 修改时间:-  /// ** 作者:sunkaixuan  /// </summary>  public class UploadFile  {    /// <summary>    /// 文件保存路径    /// </summary>    public string SetFileDirectory { get; set; }    /// <summary>    /// 允许上传的文件类型, 逗号分割,必须全部小写!    ///     /// 格式: ".gif,.exe" 或更多    /// </summary>    public string SetFileType{get;set;}    /// <summary>    /// 允许上传多少大小(单位:M)    /// </summary>    public double SetMaxSizeM {get;set;}    /// <summary>    /// 上传错误    /// </summary>    public bool GetError { get; private set; }    /// <summary>    /// 消息    /// </summary>    public string GetMessage { get; private set; }    /// <summary>    /// 文件路径    /// </summary>    public string GetFilePath { get; private set; }    /// <summary>    /// 网站路径    /// </summary>    public string GetWebFilePath { get; private set; }    /// <summary>    /// 获取文件名    /// </summary>    public string GetFileName { get; private set; }    public UploadFile()    {      SetFileDirectory = "/upload";      SetFileType = ".pdf,.xls,.xlsx,.doc,.docx,.txt";      SetMaxSizeM = 10;    }    /// <summary>    /// 单文件上传类    /// </summary>    /// <param name="directory">文件保存路径</param>    /// <param name="fileType">允许上传的文件类型</param>    /// <param name="maxSizeM">允许上传多少大小(单位:M)</param>    public UploadFile(string directory, string fileType,double maxSizeM)    {      SetFileDirectory =directory;      SetFileType = fileType;      SetMaxSizeM = maxSizeM;    }    /// <summary>    /// 保存表单文件    /// </summary>    /// <param name="formField"></param>    /// <param name="isRenameSameFile">值为true 同名文件进行重命名,false覆盖原有文件</param>    /// <param name="fileName">新的文件名</param>    /// <returns></returns>    public string Save(string formField, bool isRenameSameFile, string fileName = null)    {      try      {        var Response = HttpContext.Current.Response;        var Request = HttpContext.Current.Request;        // 获取上传的文件        HttpFileCollection File = Request.Files;        HttpPostedFile PostFile = File[formField];        //文件名        fileName = string.IsNullOrEmpty(fileName) ? PostFile.FileName : fileName;        //验证格式        this.CheckingType(PostFile.FileName);        //验证大小        this.CheckSize(PostFile);        if (GetError) return string.Empty;        string webDir = string.Empty;        // 获取存储目录        var directory = this.GetDirectory(ref webDir);        var filePath = directory + fileName;        if (System.IO.File.Exists(filePath))        {          if (isRenameSameFile)          {            filePath = directory + DateTime.Now.ToString("yyyyMMddhhssms") + "-" + fileName;          }          else          {            System.IO.File.Delete(filePath);          }        }        // 保存文件        PostFile.SaveAs(filePath);        GetFilePath = filePath;        GetWebFilePath = webDir + fileName;        GetFileName = PostFile.FileName;        return filePath;      }      catch (Exception ex)      {        TryError(ex.Message);        return string.Empty;      }    }    private void CheckSize(HttpPostedFile PostFile)    {      if (PostFile.ContentLength / 1024.0 / 1024.0 > SetMaxSizeM)      {        TryError(string.Format("对不起上传文件过大,不能超过{0}M!", SetMaxSizeM));      }    }    /// <summary>    /// 获取目录    /// </summary>    /// <returns></returns>    private string GetDirectory(ref string webDir)    {      // 存储目录      string directory = this.SetFileDirectory;      // 目录格式      string Date = DateTime.Now.ToString("yyyy-MM/dd");      webDir = directory + "/" + Date + '/';      string dir = HttpContext.Current.Server.MapPath(webDir);      // 创建目录      if (Directory.Exists(dir) == false)        Directory.CreateDirectory(dir);      return dir;    }    /// <summary>    /// 验证文件类型    /// </summary>    /// <param name="FileName"></param>    private void CheckingType(string FileName)    {      // 获取允许允许上传类型列表      string[] TypeList = this.SetFileType.Split(',');      // 获取上传文件类型(小写)      string Type = Path.GetExtension(FileName).ToLowerInvariant();      string Name = Path.GetFileNameWithoutExtension(FileName);      string NameHash = Name.GetHashCode().ToString();      // 验证类型      if (TypeList.Contains(Type) == false)        this.TryError("文件类型非法!");    }    /// <summary>    /// 抛出错误    /// </summary>    /// <param name="Msg"></param>    private void TryError(string msg)    {      this.GetError = true;      this.GetMessage = msg;    }  }}

  




原标题:ASP.NET 文件上传类 简单好用

关键词:ASP.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

必看:做外贸千万不可忽视这几个“税”:https://www.ikjzd.com/articles/98222
亚马逊卖家如何精细化做成本管理及物流费用管理?:https://www.ikjzd.com/articles/98223
亚马逊站内Deal有哪些类别?优缺点是什么?:https://www.ikjzd.com/articles/98224
阿里巴巴国际站商家星等级3.0版即将上线!:https://www.ikjzd.com/articles/98225
跨境运营关键词查找:必知的几种方法介绍!:https://www.ikjzd.com/articles/98226
盘点:B2B端产品经理要掌握的3项硬核基本功:https://www.ikjzd.com/articles/98227
湘西游轮六 湘江游轮夜游:https://www.vstour.cn/a/411226.html
携程旅游网折扣优惠最新攻略(携程旅游网更佳折扣优惠):https://www.vstour.cn/a/411227.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流