开发者

Validate FileUpload Control In ASP.Net

I want to validate asp FileUpload Control using in asp.net. That should accept only the .xlsx and .xls files. Validations may be on server side or client side. but client side will better. How 开发者_高级运维to do this?


yes.. you can validate by simple client script..

var uploadfile=document.getElementById("<%=FileUpload1.ClientID%>").value; //get substring to find out extension var ext= uploadfile.extension //get substring to find out extension
if (ext !=".xls") { alert("invalid format.") return false; }


On server side u can do it like this

 if (FileUpload1.HasFile)
 {
 string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
 if (fileExtension.ToLower() != ".xlsx" && fileExtension.ToLower() != ".xls") 
 {
 Labelupload.Text = "Only Files with ..xlsx and .xls extension are allowed";
 Labelupload.ForeColor = System.Drawing.Color.Red;

 }


Checking for a true file type is not simple. A user can spoof the file type (e.g., .exe renamed .pdf), and a malicious file will then appear as a benign one. And checking the MIME type server-side won't fix this; i.e., an .exe will show a MIME of "application/pdf" if renamed as .pdf. An easy way to check the true file type using System.IO.BinaryReader is described here using System.IO.BinaryReader:

http://forums.asp.net/post/2680667.aspx

and VB version here:

http://forums.asp.net/post/2681036.aspx

Note that you'll need to know the binary 'codes' for the file type(s) you're checking for, but you can get them by implementing this solution and debugging the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜