Asp.net MVC httppostedfilebase file upload instance code

Time:2021-6-5

This paper introduces the asp.net MVC httppostedfilebase file upload, share to you, hope to help you

Httppostedfilebase file upload, support multi file upload at one time, if there is a picture, support to save the thumbnail

Encapsulation of file transfer information

/// <summary>
  ///File generation method
  /// </summary>
  public class UpFileMessage
  {
    /// <summary>
    ///File name
    /// </summary>
    public string OriginalFileName { get; set; }

    /// <summary>
    ///Do you want to save the thumbnail
    /// </summary>
    public bool IsImage { get; set; }

    /// <summary>
    ///File stream
    /// </summary>
    public Stream FileStream { get; set; }

    /// <summary>
    ///How to generate thumbnails
    ///[wh] - specify width and height
    ///[H] - specifies the height and scales the width proportionally
    ///[w] - specifies the width and scales the height proportionally
    /// </summary>
    public string Mode { get; set; }

    /// <summary>
    ///Sketch height
    /// </summary>
    public int? ThumbHeight { get; set; }

    /// <summary>
    ///Width of thumbnail
    /// </summary>
    public int? ThumbWidth { get; set; }

  }

File upload return result

/// <summary>
  ///File upload return result
  /// </summary>
  public class UpFileResultMessage
  {
    /// <summary>
    ///Is the file saved successfully
    /// </summary>
    public bool IsSuccess { get; set; }

    /// <summary>
    ///Error message
    /// </summary>
    public string Message { get; set; }

    /// <summary>
    ///Original file name - (no extension)
    /// </summary>
    public string FileName { get; set; }

    /// <summary>
    ///File name extension
    /// </summary>
    public string FileSuffix { get; set; }

    /// <summary>
    ///File name save path
    /// </summary>
    public string FilePath { get; set; }

    /// <summary>
    ///When the file type is picture
    ///Thumbnail save path
    /// </summary>
    public string ThumbPath { get; set; }

    /// <summary>
    ///Save file name (no extension)
    /// </summary>
    public string SaveFileName { get; set; }

    /// <summary>
    ///Add file ID
    /// </summary>
    public int[] FileIdArray { get; set; }
  }

File upload class library

You need to refer to the system. Web namespace, inherit [system. Web. UI. Page], and call the server. Mappath method

public class FileUtil : System.Web.UI.Page
  {
    /// <summary>
    ///Picture upload
    /// </summary>
    ///< param name = "filemessage" > file generation method < / param >
    /// <returns></returns>
    public UpFileResultMessage UpLoadFile(UpFileMessage fileMessage)
    {
      try
      {
        string now = DateTime.Today.ToString("yyyyMMdd");
        string guid = Guid.NewGuid().ToString();

        //Get file extension
        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);
        }

        //Save file name
        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);
            }
          }
          //When uploading a file as a picture, you need to create a thumbnail
          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": // specifies the height width scaling (possible deformation) 
                  thumbWidth = fileMessage.ThumbWidth.HasValue ? fileMessage.ThumbWidth.Value : 200;
                  thumbHeight = fileMessage.ThumbHeight.HasValue ? fileMessage.ThumbHeight.Value : 200;
                  break;
                Case "W": // specify width and height in proportion   
                  thumbWidth = fileMessage.ThumbWidth.HasValue ? fileMessage.ThumbWidth.Value : 200;
                  thumbHeight = height * thumbWidth / width;
                  break;
                Case "H": // specify the height and width in proportion
                  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>
    ///Creates a thumbnail of the specified picture file stream
    /// </summary>
    ///< param name = "thumbfilepath" > save path of thumbnail file < / param >
    ///< param name = "FileStream" > original file stream < / param >
    ///< param name = "width" > thumbnail width < / param >
    ///< param name = "height" > thumbnail 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);
        }
      }

    }

  }

Call mode


var upFileMsg = new UpFileMessage()
          {
            IsImage = true,
            OriginalFileName = platformImg[i].FileName,
            FileStream = platformImg[i].InputStream,
            ThumbWidth = ThumbWidth,
            Mode = "W"
          };
         var  upFileResultMsg = new FileUtil().UpLoadFile(upFileMsg);

Code address:File upload class library package.zip 

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.