Image upload common types of judging methods have so many---intercept extension, get file contenttype (MIME), read byte to judge (what is the name of this?). )。 There are security issues in the first two. Easy to upload unsafe files, such as Trojans or something. The 1th kind of interception file extension to judge the method is obviously unsafe, the 2nd kind of contenttype MIME can be forged, so use ContentType to judge is actually not safe. It is recommended to adopt the 3rd type.
C # Demo:
1. It is not advisable to intercept extensions to make judgments.
if(Request.Files.Count >0){ //only Test upload the first picture here File[0]Httppostedfile FILE0 = request.files[0]; stringext = 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 File} Else{Response.Write ("The picture is not formatted correctly"+ext); }}
2. Judge ContentType (MIME), which is safer than the 1th option. But in fact ContentType can be forged, so it is not safe enough.
if(Request.Files.Count >0){//only Test upload the first picture here File[0]Httppostedfile FILE0 = request.files[0]; stringContentType = 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 ("The picture is not formatted correctly"+ContentType); }}
3. Get the file type by byte to make a judgment.
if(Request.Files.Count >0){//only Test upload the first picture here File[0]Httppostedfile FILE0 = request.files[0]; //Convert to Byte, read picture MIME type stream stream; //int contentlength = FILE0. ContentLength; //file length byte[] filebyte = newbyte[2];//ContentLength, here we only read the file length of the first two bits used to judge the good, so faster, the rest is not used. stream =FILE0. InputStream; Stream. Read (Filebyte,0,2);//ContentLength, or take the top two stream. Close (); stringFileflag =""; if(Filebyte! =NULL&& filebyte.length >0)//whether the picture data is empty {Fileflag = filebyte[0]. ToString () + filebyte[1]. ToString (); } string[] Filetypestr = {"255216","7173","6677","13780"};//corresponding picture format jpg,gif,bmp,pngif (Filetypestr.contains (fileflag)){File0. SaveAs (Server.MapPath ("~/"+FILE0. FileName)); } Else{Response.Write ("The picture is not formatted correctly:"+Fileflag); }}
Picture upload security issue, according to ContentType (MIME) judge is actually inaccurate, unsafe