是HttpPostedFile.ContentType验证上传的文件一个完美的方式? [英] Is HttpPostedFile.ContentType a flawless way to validate an uploaded file?

查看:807
本文介绍了是HttpPostedFile.ContentType验证上传的文件一个完美的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要验证的文件类型,以确保用户上传类型JPEG,GIF或PNG的图片。而不是检查文件扩展名的,我想用HttpPostedFile.ContentType,因为它会检查MIME内容类型会更安全。

I want to validate the file type to make sure the user is uploading an image of type JPEG, GIF, or PNG. Instead of checking the file extension, I figured using HttpPostedFile.ContentType would be safer since it checks the MIME content type.

protected void cvValidateImageType_ServerValidate(object source, ServerValidateEventArgs args)
{
    if (fupImage.HasFile)
    {
        args.IsValid = (fupImage.PostedFile.ContentType.ToLower() == "image/jpg" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/jpeg" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/pjpeg" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/gif" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/x-png" ||
                        fupImage.PostedFile.ContentType.ToLower() == "image/png");

    }
    else
        args.IsValid = true;
}

这是一个完美的方式来检查文件类型,还是可以被愚弄?

Is this a flawless way to check the file type, or can it be fooled?

推荐答案

使用扩展可能是更安全的。所述的ContentType在来自客户端的HTTP请求发送。如果测试的扩展,用户可以改变一个exe为JPG的扩展,但它不会运行作为一个exe。

Using the extension is probably safer. The ContentType is sent in the http request from the client. If you test for the extension, the user can change the extension of an exe to jpg, but it won't run as an exe.

这篇关于是HttpPostedFile.ContentType验证上传的文件一个完美的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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