登录  /  注册

HttpPostedFileBase文件上传实例详解

零下一度
发布: 2018-05-11 11:35:29
原创
13025人浏览过

这篇文章主要介绍了asp.net mvc 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);
登录后复制

以上就是HttpPostedFileBase文件上传实例详解的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号