• OnClientClick知识+一个上传的例子


    文件名:<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:asp456.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>");
    }
    }

  • 相关阅读:
    20150515
    20150509
    20150507
    好用的log打印类
    20150429
    Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
    word无法切换中文输入法的解决方法
    20140917设置动态壁纸
    WCF入门教程(三)定义服务协定--属性标签
    WCF入门教程(二)从零做起-创建WCF服务
  • 原文地址:https://www.cnblogs.com/ZkbFighting/p/8143228.html
Copyright © 2020-2023  润新知