美文网首页
Html5 图片上传和预览 FileReader

Html5 图片上传和预览 FileReader

作者: 玲珑花 | 来源:发表于2017-10-24 11:07 被阅读0次

Html5 图片上传和预览 New FileReader()的使用
将图片以base64编码格式变为字符串,以此实现图片的预览功能

<!doctype html>
<html>

    <head>
        <meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
        <title>上传图片显示缩略图</title>
    </head>

    <body>
        <form name="uploadForm">
            <table>
                <tbody>
                    <tr>
                        <td><img id="uploadPreview" style="width: 100px; height: 100px;" src="" /></td>
                        <td><input id="uploadImage" type="file" name="myPhoto" onchange="loadImageFile();" /></td>
                    </tr>
                </tbody>
            </table>
        </form>
        <script>
            var fileReader = new FileReader();
            fileReader.onload = function(event) {
                document.getElementById("uploadPreview").src = event.target.result;
            }

            function loadImageFile() {
                var file = document.getElementById("uploadImage").files[0];
                if(file) {
                    fileReader.readAsDataURL(file);
                }
            }
        </script>
    </body>

</html>

运行效果示意图

Paste_Image.png

注意:
IE10以下的版本不支持FileReader()构造函数。

详情可见api解释
https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader

相关文章

网友评论

      本文标题:Html5 图片上传和预览 FileReader

      本文链接:https://www.haomeiwen.com/subject/gestpxtx.html