ASP. NET Upload File Format Correct and Safe by byte
- 2021-07-13 05:00:50
- OfStack
When judging the file format in ASP. NET, we used to judge by intercepting the extension or by ContentType (MIME). These two methods are not safe, because users can forge them in both ways, so as to attack websites and achieve the purpose of hanging horses on websites.
The following describes how to get the file type through byte to make a judgment
if (Request.Files.Count > 0)
{
// Here only test the upload 1 A picture file[0]
HttpPostedFile file0 = Request.Files[0];
// Convert to byte, Read a picture MIME Type
Stream stream;
//int contentLength = file0.ContentLength; // File length
byte[] fileByte = new byte[2];//contentLength Here, we only read the first two bits of the file length for judgment, so the speed is faster, and 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(" The picture format is incorrect :" + fileFlag);
}
}
byte data corresponding to common file types
199196 | sqlite数据库文件 |
7076 | flv视频文件 |
6787 | swf视频文件 |
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种子 |
64101 | bat |
255254 | csv |
3780 |