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

ASP.NET MVC HttpPostedFileBase文件上传的实例代码

程序员文章站 2023-02-15 19:09:30
本文介绍了asp.net mvc httppostedfilebase文件上传 ,分享给大家,希望对大家有帮助 httppostedfilebase文件上传,支持多文件一...

本文介绍了asp.net mvc httppostedfilebase文件上传 ,分享给大家,希望对大家有帮助

httppostedfilebase文件上传,支持多文件一次上传,如有图片,则支持略缩图保存

文件传输信息封装

/// <summary>
  /// 文件生成方式
  /// </summary>
  public class upfilemessage
  {
    /// <summary>
    /// 文件名
    /// </summary>
    public string originalfilename { get; set; }

    /// <summary>
    /// 是否保存略缩图
    /// </summary>
    public bool isimage { get; set; }

    /// <summary>
    /// 文件流
    /// </summary>
    public stream filestream { get; set; }

    /// <summary>
    /// 生成缩略图的方式
    /// [wh]-指定宽高
    /// [h]-指定高,按比例缩放宽
    /// [w]-指定宽,按比例缩放高
    /// </summary>
    public string mode { get; set; }

    /// <summary>
    /// 略缩图高度
    /// </summary>
    public int? thumbheight { get; set; }

    /// <summary>
    /// 略缩图宽度
    /// </summary>
    public int? thumbwidth { get; set; }

  }

文件上传返回结果

/// <summary>
  /// 文件上传返回结果
  /// </summary>
  public class upfileresultmessage
  {
    /// <summary>
    /// 文件保存是否成功
    /// </summary>
    public bool issuccess { get; set; }

    /// <summary>
    /// 错误消息
    /// </summary>
    public string message { get; set; }

    /// <summary>
    /// 原始文件名-(无扩展名)
    /// </summary>
    public string filename { get; set; }

    /// <summary>
    /// 文件名扩展名
    /// </summary>
    public string filesuffix { get; set; }

    /// <summary>
    /// 文件名保存路径
    /// </summary>
    public string filepath { get; set; }

    /// <summary>
    /// 文件类型为图片时
    /// 缩略图保存路径
    /// </summary>
    public string thumbpath { get; set; }

    /// <summary>
    /// 保存文件名(无扩展名)
    /// </summary>
    public string savefilename { get; set; }

    /// <summary>
    /// 文件自增id
    /// </summary>
    public int[] fileidarray { get; set; }
  }

文件上传类库

需引用system.web命名空间,并对 [system.web.ui.page] 进行继承,调用server.mappath方法

public class fileutil : system.web.ui.page
  {
    /// <summary>
    /// 图片上传
    /// </summary>
    /// <param name="filemessage">文件生成方式</param>
    /// <returns></returns>
    public upfileresultmessage uploadfile(upfilemessage filemessage)
    {
      try
      {
        string now = datetime.today.tostring("yyyymmdd");
        string guid = guid.newguid().tostring();

        //获取文件扩展名
        var filesuffix = path.getextension(filemessage.originalfilename);

        var uploadfolder = path.combine(system.web.httpcontext.current.server.mappath(parmsconfig.upfilepathurl), now);

        if (!directory.exists(uploadfolder))
        {
          directory.createdirectory(uploadfolder);
        }

        //保存文件名
        string savefilename = guid + filesuffix;
        string filepath = path.combine(uploadfolder, savefilename);


        upfileresultmessage upfileresult = new upfileresultmessage()
        {
          issuccess = true,
          filename = path.getfilenamewithoutextension(filemessage.originalfilename),
          filesuffix = filesuffix,
          filepath = string.format(@"{0}/{1}", parmsconfig.upfileipaddressurl, now),
          savefilename = guid
        };

        using (stream sourcestream = filemessage.filestream)
        {
          using (filestream targetstream = new filestream(filepath, filemode.create, fileaccess.write, fileshare.none))
          {
            const int bufferlen = 1024 * 4;//4kb
            byte[] buffer = new byte[bufferlen];
            int count = 0;
            while ((count = sourcestream.read(buffer, 0, bufferlen)) > 0)
            {
              targetstream.write(buffer, 0, count);
            }
          }
          //上传文件为图片时,需创建缩略图
          if (filemessage.isimage)
          {
            var uploadthumbfolder = path.combine(uploadfolder, "thumb");

            if (!directory.exists(uploadthumbfolder))
            {
              directory.createdirectory(uploadthumbfolder);
            }
            using (filestream targetstream = new filestream(filepath, filemode.open, fileaccess.read, fileshare.none))
            {
              system.drawing.image image = system.drawing.image.fromstream(targetstream);
              int width = image.width;
              int height = image.height;
              int thumbwidth = 0;
              int thumbheight = 0;
              switch (filemessage.mode)
              {
                case "wh": //指定高宽缩放(可能变形) 
                  thumbwidth = filemessage.thumbwidth.hasvalue ? filemessage.thumbwidth.value : 200;
                  thumbheight = filemessage.thumbheight.hasvalue ? filemessage.thumbheight.value : 200;
                  break;
                case "w":  //指定宽,高按比例   
                  thumbwidth = filemessage.thumbwidth.hasvalue ? filemessage.thumbwidth.value : 200;
                  thumbheight = height * thumbwidth / width;
                  break;
                case "h":  //指定高,宽按比例
                  thumbheight = filemessage.thumbheight.hasvalue ? filemessage.thumbheight.value : 200;
                  thumbwidth = width * thumbheight / height;
                  break;
                default:
                  thumbwidth = filemessage.thumbwidth.hasvalue ? filemessage.thumbwidth.value : 200;
                  thumbheight = height * thumbwidth / width;
                  break;
              }
              string thumbfilepath = path.combine(uploadthumbfolder, savefilename);
              createthumbnail(thumbfilepath, targetstream, thumbwidth, thumbheight);
              upfileresult.thumbpath = string.format(@"{0}/{1}/thumb", parmsconfig.upfileipaddressurl, now);
            }
          }
        }

        return upfileresult;
      }
      catch (exception ex)
      {
        return new upfileresultmessage() { issuccess = false, message = ex.message };
      }

    }

    /// <summary>
    /// 创建指定图片文件流的缩略图
    /// </summary>
    /// <param name="thumbfilepath">缩略图文件保存路径</param>
    /// <param name="filestream">原始文件流</param>
    /// <param name="width">缩略图宽</param>
    /// <param name="height">缩略图高</param>
    private void createthumbnail(string thumbfilepath, stream filestream, int width, int height)
    {
      using (image image = image.fromstream(filestream))
      {
        using (image thumbnail = image.getthumbnailimage(width, height, null, intptr.zero))
        {
          thumbnail.save(thumbfilepath);
        }
      }

    }

  }

调用方式

var upfilemsg = new upfilemessage()
          {
            isimage = true,
            originalfilename = platformimg[i].filename,
            filestream = platformimg[i].inputstream,
            thumbwidth = thumbwidth,
            mode = "w"
          };
         var  upfileresultmsg = new fileutil().uploadfile(upfilemsg);

代码地址:文件上传类库包.zip 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。