aspx 代码
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>无标题页</title>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:FileUploadID="FileUpLoad1"runat="server"/>
<br/>
<asp:ButtonID="btnFileUpload"runat="server"
OnClick="btnFileUpload_Click"Text="文件上传"
OnClientClick="return checkType()"/>
<asp:LabelID="lblMessage"runat="server"></asp:Label>
</div>
</form>
</body>
</html>
js代桐枣码
function checkType(){
//得到上传文件的值
var fileName=document.getElementById("FileUpLoad1").value;
//返回String对象中子字符串最后出橡轮现的位置.
var seat=fileName.lastIndexOf(".");
//返回位于String对象中指定位置的子字符串并转换为小写.
var extension=fileName.substring(seat).toLowerCase();
//判局如拆断允许上传的文件格式
//if(extension!=".jpg"&&extension!=".jpeg"&&extension!=".gif"&&extension!=".png"&&extension!=".bmp"){
//alert("不支持"+extension+"文件的上传!");
//return false;
//}else{
//return true;
//}
var allowed=[".jpg",".gif",".png",".bmp",".jpeg"];
for(var i=0;i<allowed.length;i++){
if(!(allowed[i]!=extension)){
returntrue;
}
}
alert("不支持"+extension+"格式");
returnfalse;
}
cs代码
//文件上传按钮click事件
protectedvoid btnFileUpload_Click(object sender, EventArgs e)
{
if (FileUpLoad1.HasFile)
{
//判断文件是否小于10Mb
if (FileUpLoad1.PostedFile.ContentLength < 10485760)
{
try
{
//上传文件并指定上传目录的路径
FileUpLoad1.PostedFile.SaveAs(Server.MapPath("~/Files/")
+ FileUpLoad1.FileName);
//当然上传语句也可以这样写(貌似废话):
//FileUpLoad1.SaveAs(@"D:\"+FileUpLoad1.FileName);
lblMessage.Text = "上传成功!";
}
catch (Exception ex)
{
lblMessage.Text = "出现异常,无法上传!";
//lblMessage.Text += ex.Message;
}
}
else
{
lblMessage.Text = "上传文件不能大于10MB!";
}
}
else
{
lblMessage.Text = "尚未选择文件!";
}
}