ASP.NET文件上传:我怎样才能确保上传的文件确实是一个JPEG? [英] ASP.NET File Upload: how can I make sure that an uploaded file is really a JPEG?

查看:115
本文介绍了ASP.NET文件上传:我怎样才能确保上传的文件确实是一个JPEG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

犯罪分子可以假冒文件的内容类型,他的上传。所以,如果我通过我的页面接收服务器上的文件,我不能只检查它的MIME类型和文件扩展名。有没有检查上传的文件实际上是在JPEG,GIF或PNG任何可靠的方法?我要拒绝所有其它格式。我可以尝试读取位的文件位,但我是什么找?感谢您的任何形式的建议或想法!

Criminals can fake the content type of the file he's uploading. So, if I receive the file on the server through my page, I cannot just check its MIME type and file extension. Is there any reliable way to check if uploaded file is in fact the JPEG, GIF or PNG? I need to reject all other formats. I could attempt to read the file bit by bit, but what am I looking for? Thanks for any kind of suggestions or ideas!

推荐答案

最简单的方法是检查输入流的报头和查找特定的签名:

The easiest way would be to check the header of the input stream and look for specific signatures:


  • JPEG:FF D8在十六进制

  • GIF:前三个字节GIF

  • PNG:十进制137 80 78 71 13 10 26 10

实例ASP.NET

        bool isValid = false;
        char[] header = new char[10];
        StreamReader sr = new StreamReader(Request.InputStream);
        sr.Read(header, 0, 10);

        // check if JPG
        if (header[0] == 0xFF && header[1] == 0xD8)
        {
            isValid = true;
        }
        // check if GIF
        else if (header[0] == 'G' && header[1] == 'I' && header[2] == 'F')
        {
            isValid = true;
        }
        // check if PNG
        else if (header[0] == 137 && header[1] == 80 && header[2] == 78 && header[3] == 71 && header[4] == 13 && header[5] == 10 && header[6] == 26 && header[7] == 10)
        {
            isValid = true;
        }

当然,你必须处理异常

of course you'll have to handle the exceptions

这篇关于ASP.NET文件上传:我怎样才能确保上传的文件确实是一个JPEG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆