This article introduces to you how to use the FileReader object to obtain the image base64 code and preview it. Friends in need can refer to it.
Use FileReader to get the image base64 and preview it on the page:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <!-- 上传图片的input 绑定onchange事件--> <form action=""> <input type="file" onchange="previewFile()" name="myfile" multiple="multiple"><br> </form> <!-- 预览的图片 --> <img src="" height="200" width="300" alt="Image preview..."/> <script type="text/javascript"> function previewFile() { var preview = document.querySelector('img'); // 选中file元素,并访问其files属性的第一个值 var file = document.querySelector('input[type=file]').files[0]; // console.log(document.querySelector('input[type=file]').files); // console.log(document.querySelector('input[type=file]').files[0]); var reader = new FileReader(); // 处理loadend事件,该事件在读取操作结束时(要么成功,要么失败)触发 reader.onloadend = function () { console.log(reader.result) preview.src = reader.result; } // 读取指定的Blob中的内容,一旦完成,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容。 reader.readAsDataURL(file); } </script> </body> </html>
Related recommendations:
FileReader in JS implements image upload preview
FileReader implements local preview before uploading pictures
The above is the detailed content of How to use FileReader object to get the code of the picture. For more information, please follow other related articles on the PHP Chinese website!