文件名:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
???????<asp:Image ID="Image1" runat="server" />
???????<br/>
????????<input type="file" name="f1" id="f1">
???????<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="return exisitExit()" />
<script>
???????function exisitExit() {
???????????var f1 = document.getElementById("f1");
??????????var ext= f1.value.substring(f1.value.lastIndexOf("."));
??????????if (ext == ".jpg" || ext == ".jpeg" || ext == ".gif") {
???????????????return true;
???????????}
???????????else {
???????????????alert("文件类型不符合人要求");
???????????????return false;
???????????}
???????}
???</script>
OnClientClick是客户端脚本,一般使用javascript,在客户端,也就是IE中运行,点击后马上执行
protected void Button1_Click(object sender, EventArgs e)
???????{
???????????//路径 文件名 扩展名 要求的存储格式~数组
???????????HttpPostedFile hf = Request.Files["f1"];
???????????string filename = hf.FileName;//全路径:F:\asp\456.jpg ??????:FileName要上传的文件所在地
???????????string Imgname = Path.GetFileName(filename);//文件名:456
???????????string ext = Path.GetExtension(Imgname).ToLower();//获取拓展名:.jpg
???????????Response.Write(Imgname + "<br/>" + ext);
???????????string[] exts = {".jpg",".jpeg",".png",".bmp",".gif" };
???????????bool tag = false;
???????????foreach (string item in exts)
???????????{
???????????????if (item == ext)
???????????????{
???????????????????tag = true;
???????????????????break;
???????????????}
???????????}
???????????if(tag) //扩展名符合要求,upload 自定义日期(dir) dirpath SaveAS(durpath+imgname)
???????????{
???????????????if (hf.ContentLength < 1024 )
???????????????{
???????????????????string uppath="upload/";
???????????????????string dir = DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day;
???????????????????string dirpath = Server.MapPath(uppath + dir);
???????????????????if (!Directory.Exists(dirpath))
???????????????????{
???????????????????????Directory.CreateDirectory(dirpath);
???????????????????}
???????????????????if (TextBox1.Text != "")
???????????????????{
???????????????????????Imgname = TextBox1.Text + ext;
???????????????????}
???????????????????hf.SaveAs(dirpath + Imgname);
???????????????????Image1.ImageUrl = uppath + dir + Imgname;
???????????????????Image1.Width = 400;
???????????????????Image1.Height = 300;
???????????????}
???????????????else
???????????????{
???????????????????Response.Write("<script>alert(‘上传文件太大‘)</script>");
???????????????}
???????????}
???????????else
???????????{
???????????Response.Write("<script>alert(‘文件格式不对‘)</script>");
???????????}
???????}
OnClientClick知识+一个上传的例子
原文地址:https://www.cnblogs.com/ZkbFighting/p/8143228.html