欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET实现的简单易用文件上传类

程序员文章站 2024-02-13 15:17:46
调用方法: uploadfile uf = new uploadfile(); /*可选参数*/ uf.setisuseoldfilename(true...

调用方法:

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