Home  >  Article  >  Web Front-end  >  jquery implements local preview function before image upload_jquery

jquery implements local preview function before image upload_jquery

WBOY
WBOYOriginal
2016-05-16 09:00:052141browse

the example in this article shares with you the specific code for jquery to preview images before uploading for your reference. the specific content is as follows
there is a small problem before the introduction. when i can't find the picture preview, the reason why the picture does not come out turns out to be the path of the picture! ! ! what i keep writing is the local path of the image, which is of no use. go directly to the code.

html part:

copy code the code is as follows:
jquery implements local preview function before image upload_jquery

input:file event is upload type
the more commonly used attribute values ​​are as follows:
accept: indicates the file mime types that can be selected. multiple mime types are separated by english commas. commonly used mime types are shown in the table below.
to support all image formats, just write *.
multiple:whether multiple files can be selected. when there are multiple files, the value is the virtual path of the first file

the style of input:file is unchanged, so if you want to change its style, hide it first. display:none;

css part:
because we are making a round avatar, we define the picture style first.

 #pic{
      width:100px;
      height:100px;
      border-radius:50% ;
      margin:20px auto;
      cursor: pointer;
    }

jquery part:

 $(function() {
   $("#pic").click(function () {
     $("#upload").click();               //隐藏了input:file样式后,点击头像就可以本地上传
      $("#upload").on("change",function(){
        var objUrl = getObjectURL(this.files[0]) ;  //获取图片的路径,该路径不是图片在本地的路径
        if (objUrl) {
          $("#pic").attr("src", objUrl) ;      //将图片路径存入src中,显示出图片
        }
     });
   });
 });

 //建立一個可存取到該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 ;
 }

the running results are as follows:

the above is the entire content of this article. i hope it will be helpful to everyone learning the jquery program.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn