How to correctly determine the upload file format for ASP

Source: Internet
Author: User

Asp. NET in judging the file format, if by intercepting extension to judge, through ContentType (MIME) judgment is not too safe, because both ways users can forge.


Here's how to get the file type by byte to make judgments

if  (request.files.count > 0) {//test only upload the first image here File[0]    httppostedfile  file0 = request.files[0];          //Conversion to Byte , read the image MIME type     stream stream;    //int contentlength =  file0. contentlength; //file Length     byte[] filebyte = new byte[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 ();          string fileflag =  "";     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,png    if   (Filetypestr.contains (fileflag))     {         file0. SaveAs (Server.MapPath ("~/"  + FILE0. FileName));    }    else    {         response.write ("Picture format is incorrect:"  + fileflag);     }}



Byte data corresponding to common file types

7076 flv video file; 6787 swf video file; 7173 gif; 255216 jpg;13780 png;6677 bmp;239187 txt,aspx, asp,sql;208207 xls.doc.ppt;6063 xml;6033 htm,html;4742 js;8075 Xlsx,zip,pptx,mmap,zip,doc X



Reference: ASP. NET to determine the upload file format http://www.studyofnet.com/news/996.html


How to correctly determine the upload file format for ASP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.