Home > Article > Backend Development > Two ways to implement image preview in javascript
This article mainly introduces two ways to implement picture preview with JS. It is very good and has reference value. Friends in need can refer to it
Considering the user experience, the web page Before uploading the image to the database, it is necessary to preview it. First, it can bring a sense of security to the user, and second, it can prevent image files from being submitted to the database due to problems and occupying storage resources.
There are two ways to implement preview: one is to use the window.URL.createObjectURl method to generate a blob object path for the selected image data (which can be barely understood as the value of the input); the second is to The first is to get the FileReader reader.
No matter which method, you must first get the file data. Obtaining the file data is obtained from the files collection.Method 1:
The code is as follows:<input type=file id="inp"> <script> inp.onchange=function(){ var file=this.files[0] // 获取input上传的图片数据; var img=new Image() ; url=window.URL.createObjectURL(file) // 得到bolb对象路径,可当成普通的文件路径一样使用,赋值给src; img.src=url; //其实也可一句代码搞定,不需要声明那么多变量;img.scr=window.URL.cteateObejectURL(this.files[0]) ; 然后把img添加到页面就实现预览了 } <script>
Method 2:
Use FileRader objectto read files. It can be divided into four steps; 1. Create FileReader Object; 2. Call the readAsDataURL method to read the file; 3. Call onload event to monitor. We need to get the complete data, but we don’t know when the file has been read? , so the third step of monitoring is needed; 4. Get the reading result through the result attribute of the FileRader object r.
The code is as follows:<input type=file id="inp"> <input type=file id="inp"> <script> inp.onchange=function(){ var read=new FileReader() // 创建FileReader对像; read.readAsDataURL(this.files[0]) // 调用readAsDataURL方法读取文件; read.onload=function(){ url=read.result // 拿到读取结果; var img=new Image(); img.src=url; p.appendChild(img); } }
The above is the detailed content of Two ways to implement image preview in javascript. For more information, please follow other related articles on the PHP Chinese website!