c multi image upload and generate thumbnail example code

  • 2020-06-03 06:15:38
  • OfStack

Foreground code:



 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     <title></title>
     <style type="text/css">
         li
         {
             list-style: none;
             padding-top: 10px;
         }
     </style>
     <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
     <script type="text/javascript">
         function ValidImage(id, msg) {
             $(id).parent().append("<span>" + msg + "</span>");
             return false;
         }
     </script>
 </head>
 <body>
     <form id="form1" runat="server" enctype="multipart/form-data" method="post">
         <div>
                       <ul>
                 <li>
                     <input type="file" id="upload1" name="upload" />
                 </li>
                 <li>
                     <input type="file" id="upload2" name="upload" />
                 </li>
                 <li>
                     <input type="file" id="upload3" name="upload" />
                 </li>
                 <li>
                     <input type="file" id="upload4" name="upload" /></li>
                 <li>
                     <input type="file" id="upload5" name="upload" />

                 </li>
                 <li>
                     <input type="submit" id="btnPostFile" runat="server" onserverclick="btnPostFile_ServerClick" value=" To upload " />
                 </li>
             </ul>
         </div>
     </form>
 </body>
 </html>

The foreground is just a few controls and an ValidImage method.

Background code:



  protected void btnPostFile_ServerClick(object sender, EventArgs e)
     {
         string filePath = Server.MapPath("/uploadImg");
         const int size = 5242880;
         if (!Directory.Exists(filePath))
         {
             Directory.CreateDirectory(filePath);
         }
         if (Request.Files.Count > 0)
         {
             for (int i = 0; i < Request.Files.Count; i++)
             {
                 HttpPostedFile postFile = Request.Files[i];
                 string uploadFileID = string.Format("#upload{0}", i + 1);  // The current upload control ID, because jquery I'm going to call it #
                 string msg = null;                 // Prompt information 
                 if (postFile.FileName.Trim().Length <= 0)
                 {
                     continue;
                 }
                 if (postFile.ContentLength > size)
                 {
                     msg = " The file is too large ";
                     Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);// Send the prompt message to the client 
                     continue;
                 }
                 string savePath = Path.Combine(filePath, postFile.FileName);        // The save address of the picture 
                 if (!File.Exists(savePath))
                 {
                     postFile.SaveAs(Path.Combine(filePath, postFile.FileName));     // If the file does not exist, save it 
                 }
                 else
                 {
                     msg = " file " + postFile.FileName + " existing ";
                     Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);// Send the prompt message to the client 
                     continue;
                 }
                 if (IsImg(savePath))            // through IsImg Method to verify that the file is an image or formatted correctly 
                 {
                     SmallImg(postFile.InputStream, postFile.FileName);
                 }
                 else
                 {
                     msg = " Can only upload JGP , PNG Type of image, please check the file format is correct ";
                     Page.ClientScript.RegisterStartupScript(GetType(), "", "ValidImage(" + uploadFileID + "," + msg + ")", true);// Send the prompt message to the client 
                     File.Delete(savePath);  // If it's not, delete it 
                 }
             }
         }
     }


  #region  Verify the format of the uploaded file 
     /// <summary>
     ///  Verify that the uploaded file is an image 
     /// </summary>
     /// <param name="FilePath"> The save path for the file </param>
     /// <returns></returns>
     private bool IsImg(string FilePath)
     {
         using (FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
         {
             bool result = false;
             BinaryReader br = new BinaryReader(fs, System.Text.Encoding.UTF8);
             string strImg = "";
             byte buffer;
             try
             {
                 buffer = br.ReadByte();
                 strImg = buffer.ToString();
                 buffer = br.ReadByte();
                 strImg += buffer.ToString();
             }
             catch
             {
                 fs.Close();
                 br.Close();

             }
             if (strImg == "255216" || strImg == "13780")// instructions 255216 is jpg;7173 is gif;6677 is BMP,13780 is PNG;7790 is exe,8297 is rar
             {
                 result = true;
             }
             return result;
         }
     }
     #endregion



   #region  Generate a thumbnail of the image 
     /// <summary>
     ///  Generate thumbnails 
     /// </summary>
     private void SmallImg(Stream oStream, string FileName)
     {
         using (System.Drawing.Image img = System.Drawing.Image.FromStream(oStream))
         {
             int newWidth = 100;
             int newHeight = 80;
             int oldWidth = img.Width;
             int oldHeight = img.Height;
             if (oldWidth > oldHeight)
             {
                 newHeight = (int)Math.Floor((double)oldHeight * (double)newWidth / (double)oldWidth);
             }
             else
             {
                 newWidth = (int)Math.Floor((double)oldWidth * (double)newHeight / (double)oldHeight);
             }
             using (Bitmap bmp = new Bitmap(newWidth, newHeight))
             {
                 using (Graphics g = Graphics.FromImage(bmp))
                 {
                     g.Clear(Color.Transparent);
                     g.InterpolationMode = InterpolationMode.High;
                     g.CompositingQuality = CompositingQuality.HighQuality;
                     g.SmoothingMode = SmoothingMode.HighQuality;
                     g.DrawImage(img, new Rectangle(0, 0, newWidth, newHeight), new Rectangle(0, 0, oldWidth, oldHeight), GraphicsUnit.Pixel);
                     string newFileName = Path.GetFileNameWithoutExtension(FileName) + "_small" + Path.GetExtension(FileName);   // Thumbnail name 
                     string filePath = Server.MapPath("/uploadImg/") + newFileName;
                     bmp.Save(filePath);
                 }
             }

         }
     }
     #endregion

The code has a lot to improve, I hope you can give me some advice.


Related articles: