如何检查上传文件的内容,而不依赖于它的扩展? [英] How to check the content of an uploaded file without relying on its extension?
问题描述
你如何去验证一个上传文件的类型,可靠不使用扩展?我猜,你必须检查页眉/读取一些字节,但我真的不知道如何去做。 IM使用C#和asp.net。
How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net.
感谢您的任何建议。
好了,从上面的链接我现在知道,我找'FF FF D8 E0'来正确识别,例如.jpg文件。
ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example.
在我的code我可以读头二字节没有问题:
In my code I can read the first twenty bytes no problem:
FileStream fs = File.Open(filePath, FileMode.Open);
Byte[] b = new byte[20];
fs.Read(b, 0, 20);
左右(并请在此处原谅我经验不足总量),但我要如何检查的字节数组是否包含FF FF D8 E0'?
so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?
推荐答案
下面对你张贴的后续问题的快速和肮脏的响应:
Here's a quick-and-dirty response to the followup question you posted:
byte[] jpg = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0 };
bool match = true;
for (int i = 0; i < jpg.Length; i++)
{
if (jpg[i] != b[i])
{
match = false;
break;
}
}
这篇关于如何检查上传文件的内容,而不依赖于它的扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!