Asp. NET in the decision file format, we used to use the method is to intercept the extension to make judgments, or by ContentType (MIME), both methods are not very safe, because the two ways users can forge, so that can attack the site, to achieve the purpose of hanging the site.
Here's how to make a judgment by getting file types in byte
if (Request.Files.Count > 0)
{
///Here only Test upload first picture file[0]
httppostedfile FILE0 = request.files[0];
Convert to Byte, read picture MIME type
stream stream;
int contentlength = File0. ContentLength; File length
byte[] filebyte = new Byte[2];//contentlength, here we read only the first two bits of the file length used for judgment, so the speed is faster and the rest is not available.
stream = File0. InputStream;
Stream. Read (filebyte, 0, 2),//contentlength, or take the first two-bit
stream. Close ();
String fileflag = "";
if (filebyte!= null && filebyte.length > 0)//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 (incorrect picture format: + Fileflag);
}
}
Byte data for common file types
199196 |
SQLite database files |
7076 |
FLV video Files |
6787 |
SWF video files |
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,docx |
8297 |
rar |
01 |
Accdb,mdb |
7790 |
Exe,dll |
5666 |
Psd |
255254 |
Rdp |
10056 |
BT seeds |
64101 |
Bat |
255254 |
Csv |
3780 |
Pdf |