Home > Article > Web Front-end > Implement jquery to preview images locally before uploading them
This time I will bring you the local preview before jquery uploads the image, and the local preview before jquery uploads the image. What are the precautions? The following is a practical case, let's take a look.
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:
<img id="pic" src="" > <input id="upload" name="file" accept="image/*" type="file" style=" display : none"/>input:file event is an upload type
The more commonly used
attributes have the following values:
accept: indicates the file MIME types that can be selected. Multiple MIME types are separated by English commas. The 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.
CSS part: Because we are making a circular avatar, we define the image 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: I believe you have mastered the method after reading the case in this article, and there will be more exciting things. Please pay attention to other related articles on php Chinese website! Recommended reading:
Uploadify implements display of progress bar to upload pictures
How to create menu link button with jQuery EasyUI plug-in
The above is the detailed content of Implement jquery to preview images locally before uploading them. For more information, please follow other related articles on the PHP Chinese website!