Home > Web Front-end > JS Tutorial > body text

How to use FileReader object to get the code of the picture

不言
Release: 2018-07-18 17:29:30
Original
1744 people have browsed it

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(&#39;img&#39;);
        // 选中file元素,并访问其files属性的第一个值
        var file  = document.querySelector(&#39;input[type=file]&#39;).files[0];
        //  console.log(document.querySelector(&#39;input[type=file]&#39;).files);
        //  console.log(document.querySelector(&#39;input[type=file]&#39;).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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!