C # upload images, generate thumbnails, and preview images,
To upload images, you need to add MIME type verification and generate small-sized images for browsing. Make the following changes based on the online code:
1
The background code is as follows:
1 /// <summary> 2 /// upload Image 3 /// </summary> 4 /// <param name = "sender"> </param> 5 // /<param name = "e"> </param> 6 protected void btnUpFile_OnClick (object sender, eventArgs e) 7 {8 if (FileUpload1.PostedFile. fileName! = "") 9 {10 if (FileUpload1.PostedFile. contentLength <= 2048000) // only images smaller than or equal to 2 MB can be uploaded 11 {12 FileExtension [] fe = {FileExtension. gif, FileExtension. jpg, FileExtension. png}; // allowed image format 13 if (FileValidation. isAllowedExtension (FileUpload1, fe) 14 {15 //} 16 // if (newFileExtensions = ". jpg "| newFileExtensions = ". gif "| newFileExtensions = ". bmp "| newFileExtensions = ". png ") // use the File suffix to check whether the class is allowed. Type 17 // {18 string sfilename = FileUpload1.PostedFile. fileName; 19 int sfilenamehz = sfilename. lastIndexOf (". ", StringComparison. ordinal); 20 string newFileExtensions = sfilename. substring (sfilenamehz ). toLower (); 21 string pa = "uploadfiles/" + DateTime. now. year + "-" + DateTime. now. month + "/"; // obtain the current year and Month as the folder name 22 if (! Directory. Exists ("~ /"+ Pa) // create the folder 23 {24 Directory. CreateDirectory (Server. MapPath ("~ /"+ Pa); 25} 26 string newFileName = DateTime. Now. ToString (" yyyyMMddHHmmss "); 27 string uppath = "~ /"+ Pa + newFileName + newFileExtensions; 28 29 Stream oStream = FileUpload1.PostedFile. inputStream; 30 System. drawing. image oImage = System. drawing. image. fromStream (oStream); 31 32 int oWidth = oImage. width; // source Image Width 33 int oHeight = oImage. height; // source Image Height 34 int tWidth = 200; // set the initial width of the thumbnail to 35 int tHeight = 200; // set the initial height of the thumbnail 36 37 // calculate the width and height of the thumbnail in proportion 38 if (oWidth> = oHeight) 39 {40 tHeight = (int) Math. Floor (Convert. toDouble (oHeight) * (Convert. toDouble (tWidth)/Convert. toDouble (oWidth); 41} 42 else 43 {44 tWidth = (int) Math. floor (Convert. toDouble (oWidth) * (Convert. toDouble (tHeight)/Convert. toDouble (oHeight); 45} 46 47 // generate thumbnail image 48 Bitmap tImage = new Bitmap (tWidth, tHeight); 49 Graphics g = Graphics. fromImage (tImage); 50 GB. interpolationMode = System. drawing. drawing2D. interpolationMode. High; // set the High quality interpolation method to 51 GB. smoothingMode = System. drawing. drawing2D. smoothingMode. highQuality; // set high quality, low speed rendering smoothness 52 GB. clear (Color. transparent); // clear the canvas and fill 53 GB with a Transparent background color. drawImage (oImage, new Rectangle (0, 0, tWidth, tHeight), new Rectangle (0, 0, oWidth, oHeight), GraphicsUnit. pixel); 54 55 string upfilepath2 = "~ /"+ Pa + newFileName +" _ m "+ newFileExtensions; // Add _ m to the original image suffix for distinguishing 56 string oFullName = Server. mapPath (uppath); 57 string tFullName = Server. mapPath (upfilepath2); 58 59 try 60 {61 // Save image 62 oImage. save (oFullName); 63 tImage. save (tFullName); 64 Image1.ImageUrl = upfilepath2; // display the thumbnail to the front-end Img control 65 txtimg. text = pa + newFileName + "_ m" + newFileExtensions; // assign the file address to the control for saving 66} 67 catch (Exception ex) 68 {69 throw new Exception ("an error occurred, saving failed! ", Ex); 70} 71 finally 72 {73 // release resource 74 oImage. dispose (); 75g. dispose (); 76 tImage. dispose (); 77} 78} 79 else 80 {81 string fileType = string. empty; 82 foreach (var fileExtension in fe) 83 {84 if (! String. isNullOrEmpty (fileType) 85 {86 fileType + = ","; 87} 88 fileType + = fileExtension; 89} 90 Response. write ("<script> alert ('file format forbidden, only" + fileType + "Format Image ') </script> "); 91} 92} 93 else 94 {95 Response. write ("<script> alert ('the file is too large, Please modify the size, do not exceed 2 mb') </script> "); 96} 97} 98} 99 enum FileExtension100 {101 Jpg = 255216,102 Gif = 7173,103 Png = 13780104} 105 // <summary> 106 // determine the actual format of the uploaded file 107 /// </summary> 108 private class FileValidation109 {110 // <summary> 111 // check whether the image format is 112, which is allowed. /// </summary> 113/ // <param name = "fu"> upload Control </param> 114 // <param name = "fileEx"> file extension </param> 115 // <returns & gt; </returns> 116 public static bool IsAllowedExtension (FileUpload fu, fileExtension [] fileEx) 117 {118 int fileLen = fu. postedFile. contentLength; 119 byte [] imgArray = new byte [fileLen]; 120 fu. postedFile. inputStream. read (imgArray, 0, fileLen); 121 MemoryStream MS = new MemoryStream (imgArray); 122 BinaryReader br = new BinaryReader (MS); 123 string fileclass = string. empty; 124 try125 {126 byte buffer = br. readByte (); 127 fileclass = buffer. toString (); 128 buffer = br. readByte (); 129 fileclass + = buffer. toString (); 130} 131 catch // (Exception ex) 132 {133 // ignored134} 135 br. close (); 136 ms. close (); 137 int num = 0; 138 int. tryParse (fileclass, out num); 139 foreach (FileExtension fe in fileEx) 140 {141 if (num = (int) fe) 142 return true; 143} 144 return false; 145} 146}