首页 > 代码库 > js实现图片预览以及上传

js实现图片预览以及上传

HTML 代码:

 <input  type="file" id="fileid" onchange="filesize(this)" runat="server" size="80" Width="200px" Height="25px"/>
  <input  type="hidden" id="hidden_s" runat="server"/>

<input id="btnUpLoad" type="button" class="btn btn-ltgreen" style="width: auto;" value="http://www.mamicode.com/上 传"  onclick="UpLoad()"   runat="server" />   <!--"-->
  <input type="button" id="clickupload" onserverclick="UploadClient"  style=" display:none" runat="server"/> 

<span id="spanText" runat="server" style="color: Red"></span> 

 

点击上传时候判断:

<script type="text/javascript">
    function UpLoad() {
        if (path == "") {   //未选中图片 不允许上传,提示用户
        document.getElementById("spanText").innerHTML="请选择要上传的图片!";
            return false;
        }
        else {
            document.getElementById("clickupload").click();  //符合上传条件 执行后台上传
            return true;
        }
    }
</script>

当file控件选中文件时候 显示文件大小,以便确定是否上传

<script type="text/javascript">
    function filesize(ele) {
        // 返回 KB,保留小数点后两位
        document.getElementById("spanText").innerHTML="";
        var size = (ele.files[0].size / 1024).toFixed(2);
        document.getElementById("hidden_s").value = http://www.mamicode.com/size;
        var show = "";
        if (size < 1024) {
            show = size + "KB";
        }
        else if (size >= 1024 && size < 1024 * 1024) {
        show = parseFloat(size / 1024).toFixed(2)+"M";
        }
        document.getElementById("picsize").innerHTML = "文件大小:" +show;
        var filepath = $("#fileid").val();
        var extStart=filepath.lastIndexOf(".");
        var ext=filepath.substring(extStart,filepath.length).toUpperCase();
      if(ext!=".GIF"&&ext!=".JPEG"&&ext!=".JPG"){
      document.getElementById("spanText").innerHTML="上传文件格式不正确,请确认!";
       return false;
       }
    }
</script>

给图片标签添加预览图片

<script>
    $("#fileid").change(function() {
        var objUrl = getObjectURL(this.files[0]);
        console.log("objUrl = " + objUrl);
        if (objUrl) {
            $("#Image1").attr("src", objUrl);
        }
    });
    //建立一個可存取到该file的url
    function getObjectURL(file) {
        var url = null;
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        }
        return url;
    }
</script>

后台实现客户端上传功能(可能有重复判断)

public void UploadClient(object sender, EventArgs e)
    {
        if (Request.Files.Count > 0)   //使用客户端实现上传功能
        {
            HttpPostedFile httppostfile = this.Request.Files[0];
            string fname = httppostfile.FileName; //获取上传文件名称
            string exten = Path.GetExtension(fname); //上传文件的后缀名
            string extension = exten.ToLower();  //或许文件后缀名
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + loginUserName;  //图片重命名
            bool bl = false;
            string[] strArr = new string[] { ".gif", ".jpeg", ".jpg" };//允许上传图片格式
            if (Convert.ToDouble(this.hidden_s.Value) <= 1024)
            {
                for (int i = 0; i < strArr.Length; i++)
                {
                    if (extension.ToLower() == strArr[i])
                    {
                        bl = true; break;
                    }
                }
                if (!bl)
                {
                    this.spanText.InnerHtml = "图片格式不对!";
                    return;
                }
            }
            else
            {
                this.spanText.InnerHtml = "图片大小超过2M!";
                return;
            }
            int index = fname.LastIndexOf("\\") + 1;
            int len = fname.Length - index;
            fname = fname.Substring(index, len);
            httppostfile.SaveAs(Server.MapPath(".") + "/upload/" + fileName + extension);//保存图片
            picurl = "~/user/upload/" + fileName + extension; //得到文件保存在服务器上的路径 记录下来以便保存到服务器
            Image1.Src = "http://www.mamicode.com/~/user/upload/" + fileName;  //上传完图片后,把上传后的图片显示在页面的图片框内
            Add(); //吧图片保存到数据库
            getUserM(); //刷新页面显示图片
            
        }
    }

 

js实现图片预览以及上传