For Image Upload security issues, the ContentType (MIME) is used to determine whether it is actually inaccurate or insecure. contenttypemime
There are several methods for determining the types of image uploads: intercepting the extension, obtaining the file ContentType (MIME), and reading bytes ?). The first two have security issues. Attackers can easily upload insecure files, such as Trojans. The methods used to determine the number of file extensions intercepted are obviously insecure. The 1st types of ContentType MIME can be forged, so it is not safe to use ContentType. It is recommended to use 3rd types.
C # Demo:
1. Intercept the extension to determine whether it is not advisable.
If (Request. files. count> 0) {// only test uploading the first image file [0] HttpPostedFile file0 = Request. files [0]; string ext = file0.FileName. substring (file0.FileName. lastIndexOf ('. ') + 1); // file extension string [] fileTypeStr = {"jpg", "gif", "bmp", "png"}; if (fileTypeStr. contains (ext) {file0.SaveAs (Server. mapPath ("~ /"+ File0.FileName); // save the file} else {Response. Write (" incorrect image format "+ ext );}}
2. Determine ContentType (MIME), which is safer than 1st solutions. In fact, ContentType can be forged, so it is not safe enough.
If (Request. files. count> 0) {// only test uploading the first image file [0] HttpPostedFile file0 = Request. files [0]; string contentType = file0.ContentType; // file type string [] fileTypeStr = {"image/gif", "image/x-png", "image/pjpeg ", "image/jpeg", "image/bmp"}; if (fileTypeStr. contains (contentType) {file0.SaveAs (Server. mapPath ("~ /"+ File0.FileName);} else {Response. Write (" incorrect image format "+ contentType );}}
3. Get the file type through byte for judgment.
If (Request. files. count> 0) {// only test uploading the first image file [0] HttpPostedFile file0 = Request. files [0]; // convert to byte to read the Stream stream of the image MIME type; // int contentLength = file0.ContentLength; // The object Length byte [] fileByte = new byte [2]; // contentLength. Stream = file0.InputStream; stream. Read (fileByte, 0, 2); // contentLength, or take the first two streams. Close (); string fileFlag = ""; if (fileByte! = Null & fileByte. length> 0) // whether the image data is null {fileFlag = fileByte [0]. toString () + fileByte [1]. toString ();} string [] fileTypeStr = {"255216", "7173", "6677", "13780"}; // jpg, gif, bmp, png if (fileTypeStr. contains (fileFlag) {file0.SaveAs (Server. mapPath ("~ /"+ File0.FileName);} else {Response. Write (" incorrect image format: "+ fileFlag );}}