2011-12-05 136 views
0

我想限制上传到我的网站的文件类型。我在下面使用这个函数。如果陈述为.jpg || .gif || .jpeg || .png,我会写吗? 我不希望人们上传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."; 
} 
+0

我不认为有任何其他方式比看文件的集合看到已经上传的文件类型来上传。这很容易做到,但不幸的是这意味着您只能检查这个AFTER文件是否已经发送。在较新的浏览器中,您可以指定允许在客户端上显示FILE控件的文件扩展名。 –

回答

1

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

+0

你有一个简单的例子来说明如何做到这一点?对Csharp很新颖。 – CsharpBeginner

+0

抱歉,从未与C#亲自合作过。这只是一般性的建议。永远不要相信远程用户发送的任何内容,特别是在表单数据和文件上传时。 –

+0

几年前,我写了一个[小内容检测库](http://www.codeproject.com/KB/cs/ContentDetectorLib.aspx),这可能有助于作为首发。 –

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; 
} 
相关问题