限制要上载的文件类型

时间:2011-12-05 01:06:05

标签: c# file-upload file-extension

我想限制上传到我网站的文件类型。我在下面使用此功能。我会为.jpg || .gif || .jpeg || .png编写if语句吗? 我不希望有人上传exe。这样做的最佳方式是什么?

if (FileUpload1.HasFile)
    try
    {
        var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
        var Myguid = Guid.NewGuid().ToString("N");

        //Check to make sure its an allowable file to be uploaded???????????        

        var newName = Guid.NewGuid() + FileExtension;
        //Map path to folder
        string realpath = Server.MapPath("Pictures\\") + newName;

        //FileUpload1.SaveAs("C:\\Users\\josh\\Desktop\\JaysVersion\\PicRatingSite\\PicRatingSite\\Pictures" + FileUpload1.FileName);
        FileUpload1.SaveAs(realpath);

        Label1.Text = "File name: " +
             FileUpload1.PostedFile.FileName + "<br>" +

             FileUpload1.PostedFile.ContentLength + " kb<br>" +
             "Content type: " +
             FileUpload1.PostedFile.ContentType;


        InsertMembers insert = new InsertMembers();
        int age = Int32.Parse(txtAge.Text);
        insert.InsertNewMember(txtEmail.Text, Myguid, txtName.Text, txtCity.Text, txtState.Text, txtDescription.Text, age, gender);


        //Get Member Id to Insert into Pictures table
        GetMemberInfo GetID = new GetMemberInfo();
        int UMemberId = GetID.GetMemberId(Myguid);
        Displayme.Text = newName.ToString();

        //Now that i have member Id Lets insert new picture into picture table
        Picture InsertnewPictures = new Picture();
        int insertpics = InsertnewPictures.InserNewPicture(UMemberId, newName, 0);

    }
    catch (Exception ex)
    {
        //Handle the error
        throw ex;
    }
else
{
    Label1.Text = "You have not specified a file.";
}

2 个答案:

答案 0 :(得分:1)

不要信任用户提供的文件名。攻击是微不足道的,有人可以在上传之前轻松“重命名nastyvirus.exe cutekittens.jpg”。您必须使用服务器端mime类型检测来确保您确实获得了图像。对于远程浏览器提供的MIME类型也是如此。它也可以简单地伪造,并使“nastyvirus.exe”显示为“text / plain”。

答案 1 :(得分:0)

您可以使用switch语句过滤要上传的文件类型

var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);

switch(FileExtension.ToLower())
{
    case".jpg":
    case".png":
    case".gif":
    case".jpeg":
        break;
     default:
        Response.Write("this file type is not allowed");
        return;
}