The FileUpload class of Asp.Net implements uploading file instances

  • 2021-01-19 22:13:31
  • OfStack

This article illustrates how the FileUpload class of Asp.Net implements the method of uploading files. Share with you for your reference.

Specific functional codes are as follows:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO; namespace CSFramework.BLL
{
   /// <summary>
   /// The type of file that supports uploading
   /// </summary>
   public enum UploadFileType
   {
      ArticleAttachment = 1,
      Image = 2,
      Video = 3,
      All = 4
   }
  
   /// <summary>
   /// Upload file management class
   /// </summary>
   public class CFileUpload
   {
      private FileUpload _fileUpload;
      private string _savePath;
      private string _LastUploadedFile = string.Empty;
      private bool _AutoGenFileName = false;
      private bool _AutoGenWatermark = false;
      public string LastUploadedFile { get { return _LastUploadedFile; } }
      private string _Error = "";
     
      private string PICTURE_FILE = "[.gif.png.jpeg.jpg]";
      private string ZIP_FILE = "[.zip.rar]";
      private string MUILT_MEDIA_FILE = "[.mpeg.mpg.fla.wma]";
     
      private int IMG_MAX_WIDTH = 700;// Specifies the width of the
      private int IMG_MAX_HEIGHT = 0;// Unspecified height
      private int MAX_SIZE_UPLOAD = 1024;// Maximum support for uploads is less than 1MB The file.
     
      /// <summary>
      /// The constructor
      /// </summary>
      /// <param name="fileUpload">Asp.net FileUpload object </param>
      /// <param name="savePath"> Save the directory without the file name </param>
      /// <param name="autoGenFileName"> Automatic file name generation </param>
      public CFileUpload(FileUpload fileUpload, string savePath, bool autoGenFileName, bool autoGenWatermark)
      {
         _savePath = savePath;
         _fileUpload = fileUpload;
         _AutoGenFileName = autoGenFileName;
         _AutoGenWatermark = autoGenWatermark;
      }
     
      /// <summary>
      /// The constructor
      /// </summary>
      /// <param name="fileUpload">Asp.net FileUpload object </param>
      /// <param name="savePath"> Save the directory without the file name </param>
      public CFileUpload(FileUpload fileUpload, string savePath)
      {
         _savePath = savePath;
         _fileUpload = fileUpload;
      }
     
      /// <summary>
      /// upload RAR file
      /// </summary>
      public bool UploadRARFile()
      {
         return DoUpload(ZIP_FILE);
      }
     
      /// <summary>
      /// Upload Video Files
      /// </summary>
      public bool UploadVideo()
      {
         return DoUpload(MUILT_MEDIA_FILE);
      }
     
      /// <summary>
      /// Upload picture file
      /// </summary>
      public bool UploadImage()
      {
         return DoUpload(PICTURE_FILE);
      }
     
      public bool UploadImage(int maxWidth, int maxHeight)
      {
         this.IMG_MAX_WIDTH = maxWidth;
         this.IMG_MAX_HEIGHT = maxHeight;
         return DoUpload(PICTURE_FILE);
      }
     
      /// <summary>
      /// Upload any supported files
      /// </summary>
      public bool UploadAnySupported()
      {
         return DoUpload(PICTURE_FILE ZIP_FILE MUILT_MEDIA_FILE);
      }
     
      /// <summary>
      /// Generate a new file name
      /// </summary>
      private string GetNewFileName(string folder, string fileName)
      {
         if (_AutoGenFileName) // Automatically generate 32 position GUID The file name
         {
            string ext = System.IO.Path.GetExtension(fileName);
            string newfile = Guid.NewGuid().ToString().Replace("-", "") ext;
            return folder newfile;
         }
         else
         {
            if (System.IO.File.Exists(folder fileName))
            {
               string ext = System.IO.Path.GetExtension(fileName);
               string filebody = fileName.Replace(ext, "");
              
               int x = 1;
               while (true) // If the file exists, a tailband is generated (x) The file
               {
                  string newfile = folder filebody "(" x.ToString() ")" ext;
                  if (!System.IO.File.Exists(newfile))
                  return folder filebody "(" x.ToString() ")" ext;
                  else
                  x ;
               }
            }
            else
            return folder fileName;
         }
      }
     
      /// <summary>
      /// Maximum support is less than 1MB The file.
      /// </summary>
      private bool AllowMaxSize(int fileLength)
      {
         double kb = fileLength / 1024;
         return (int)kb < MAX_SIZE_UPLOAD;
      }
     
      private bool DoUpload(string allowedExtensions)
      {
         try
         {
            bool fileOK = false;
           
            if (!_fileUpload.HasFile) throw new Exception(" No papers! "); // If no file is included in the upload control, exit
           
            // Get the suffix of the file
            string fileExtension = System.IO.Path.GetExtension(_fileUpload.FileName).ToLower();
           
            // See if the included file is a allowed file suffix
            fileOK = allowedExtensions.IndexOf(fileExtension) > 0;
            if (!fileOK) throw new Exception(" Unsupported file format! ");
           
            // Check the size of the uploaded file
            fileOK = AllowMaxSize(_fileUpload.FileBytes.Length);
            if (!fileOK) throw new Exception(" The image file cannot be larger than " MAX_SIZE_UPLOAD.ToString() "KB ! ");
           
            try
            {
               // The file is stored separately in the directory specified by the server
               string savefile = GetNewFileName(_savePath, _fileUpload.FileName);
              
               if (IsUploadImage(fileExtension))// Save the picture
               {
                  System.Drawing.Image output = CImageLibrary.FromBytes(_fileUpload.FileBytes);
                 
                  // Check the image width / highly / The size of the
                  if (this.IMG_MAX_WIDTH != 0 && output.Width > this.IMG_MAX_WIDTH)
                  {
                     output = CImageLibrary.GetOutputSizeImage(output, this.IMG_MAX_WIDTH);
                  }
                 
                  Bitmap bmp = new Bitmap(output);
                 
                  this.CreateDir(Path.GetDirectoryName(savefile));
                 
                  bmp.Save(savefile, output.RawFormat);
                  bmp.Dispose();
                  output.Dispose();
                 
                  if (_AutoGenWatermark)
                  {
                     WatermarkImage genWatermark = new WatermarkImage();
                     genWatermark.DrawWords(savefile, AppConfig.Current.WatermarkMain,
                     AppConfig.Current.WatermarkDesc, float.Parse("0.2"));
                  }
               }
               else// Any other documents
               {
                  this.CreateDir(Path.GetDirectoryName(savefile));
                 
                  _fileUpload.PostedFile.SaveAs(savefile);
               }
              
               _LastUploadedFile = savefile;
              
               return true;
            }
            catch (Exception ex)
            {
               throw new Exception(" Unknown error while uploading file! " ex.Message);
            }
         }
         catch (Exception ex)
         {
            _Error = ex.Message;
            return false;
         }
      }
     
      private void CreateDir(string dir)
      {
         if (Directory.Exists(dir) == false)
         Directory.CreateDirectory(dir);
      }
     
      private bool IsUploadImage(string fileExtension)
      {
         bool isImage = PICTURE_FILE.IndexOf(fileExtension) > 0;
         return isImage;
      }
   }
}

I hope this article is helpful to the asp.net program design.


Related articles: