This article describes how to implement the local preview function before uploading images based on jquery, interested friends can refer to the examples in this article to share with you the specific code of jquery to implement Picture preview before uploading for your reference. The specific content is as follows:
There was a small problem before the introduction. The reason why the image cannot be previewed is that the path of the image exists !!! The local path of the image is always written, which is useless. Directly add the code.
Html section:
The Code is as follows:
Input: The file event is of the upload type.
The commonly used attribute values are as follows:
Accept:Optional file MIME types. multiple MIME types are separated by commas. The following table lists common MIME types.
To support all image formats, write.
Multiple:Whether multiple files can be selected. When multiple files are selected, the value is the virtual path of the first file.
Input: The file style remains unchanged. To change the style, first hide it. Display: none;
CSS section:
Because it is a circular Avatar, you must first define the image style.
#pic{ width:100px; height:100px; border-radius:50% ; margin:20px auto; cursor: pointer; }
JQuery section:
$ (Function () {$ ("# pic "). click (function () {$ ("# upload "). click (); // After the input: file style is hidden, click the Avatar to upload $ ("# upload") locally "). on ("change", function () {var objUrl = getObjectURL (this. files [0]); // obtain the image path, which is not the local path of the image if (objUrl) {$ ("# pic "). attr ("src", objUrl); // Save the image path to src to display the image }});});}); // create a 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 result is as follows:
The above is all of the content in this article. I hope it will help you learn jquery.