图片上传预览原理及实现

来源:互联网 发布:asp.net mvc5 web编程 编辑:程序博客网 时间:2024/06/05 07:48

目前网上有很多支持图片上传时进行预览的插件,功能完备,界面优雅,使用起来也很方便。一直以来也就只是用用,没有想过这些插件背后的实现原理。趁着今天有点时间,也来学习学习。

追根溯源

设想

一开始,按照我的思路,预览可能是这么来实现的。本地选中一张图片,嵌入html的同时会显示图片的本地的绝对路径,然后通过js简单的进行设置,应该就可以实现预览效果了。

但是实际上,目前只有低版本的IE浏览器才能实现这么个效果。究其原因是浏览器厂商为了进一步强化安全,限制了file标签直接读取本地路径的能力,在HTML5下只有通过FileReader的API来实现这一需求了。 
比如对于CSDN写博客的时候上传一张图片,得到的只会是一个fakepath。有图为证: 
file标签被限制读取本地绝对路径

原理

FileReader就是html5为我们提供的读取文件的api。它的作用就是把文本流按指定格式读取到缓存,以供js调用。

FileReader有四种读取文件的方式:

  1. readAsBinaryString读取为二进制码

  2. readAsDataURL读取为 DataURL

  3. readAsText读取为文本

  4. readAsArrayBuffer

根据本次实现的目标,使用第二种方式即可。img标签的src就是这个图片的编码后的DataURL。如图所示: 
编码后的图片src

DataURL浅析

DataURL 说来可是有很多内容要研究的,但是这次用的比较浅显,就把基础的了解下就行了。

格式

DataURL有其固定的格式,如下:

data:[文件格式];base64,[文本流base64编码]。

举个例子:

  • jpg格式: data:image/jpeg;base64,/9j/4...
  • png格式: data:image/png;base64,iVBORw...
  • gif格式: data:image/gif;base64,R0lGOD...

  • png格式的图片编码信息

png 格式的编码格式

预览实现

好了,弄明白了这些原理性的东西,就可以着手进行实现了。

HTML

<form action="#" method="POST">    <legend>        图片上传    </legend>    <fieldset>        <input type="file" name="pic1" id="pic1" onchange="preview(this)" multiple="multiple"               accept="image/x-png, image/jpg, image/jpeg, image/gif">        <br><br>    </fieldset>    <input type="button" value="上传"></form><div id="container"></div>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在代码中使用了Html5的一些新特性。用来过滤待上传的图片格式。

JavaScript控制

接下来就是预览功能的实现了。目标就是将图片转换成DataURL,然后对预览区进行子元素的添加操作。

<script>    var msg = "您可以上传png, jpg, 或者gif格式的图片";    var filter = {        "jpeg": "/9j/4",        "gif": "R0lGOD",        "png": "iVBORw"    };    function preview(file) {        var container = document.getElementById("container");        container.innerHTML = "";        if (window.FileReader) {            for (var index=0, f; f = file.files[index]; index++) {                var filereader = new FileReader();                filereader.onload = function (event) {                    var srcpath = event.target.result;                    if (!validateImg(srcpath)) {                        console.log("H5"+msg);                    } else {                        showPreviewImage(srcpath);                    }                };                filereader.readAsDataURL(f);            }        } else {            if (!/\.jpg$|\.png$|\.gif$/i.test(file.value)) {                console.log("原生"+msg);            } else {                showPreviewImage(file.value);            }        }    }    function validateImg(data) {        console.log(data);        var pos = data.indexOf(",") + 1;        for (var e in filter) {            if (data.indexOf(filter[e]) === pos) {                return e;            }        }        return null;    }    function showPreviewImage(src) {        console.log(src);        var img = document.createElement('img');        img.src = src;        img.style = "width:64px;height:auto;"        container.appendChild(img);    }</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56

预览效果

总的来说代码就算是完成了,接下来看下实现的效果。由于没有设置样式,所以看起来很简陋,有兴趣的自己用样式控制一下即可。 
图片上传预览实现

打包封装

简易封装

为了方便实用,特使用原生JavaScript封装了一个这样的组件。详细代码如下:

/** * Created by biao on 2017/7/10. * Description: A simple tool for previewing images for uploading. * Blog: http://blog.csdn.net/marksinoberg * GitHub: https://github.com/guoruibiao */function ImgPrevirewer(config) {    /**     * The tag ID for upload images.     */    this.fileId = config.fileId;    /**     * tip for error message.     * @type {string}     */    this.tip = config.tip;    /**     * The ID for the container which contains img tags.     * @type {string}     */    this.containerId = config.containerId;    /**     * CSS style for previewing imgs.     * @type {string}     */    this.imgStyle = config.imgStyle;    /**     * 过滤图片格式,可进行相对应的删减操作。     * @type {{jpeg: string, gif: string, png: string}}     */    this.filter = {        /**         * jpg或者jpeg格式的图片。         */        "jpeg": "/9j/4",        /**         * gif格式的图片。         */        "gif": "R0lGOD",        /**         * PNG格式的图片。         */        "png": "iVBORw"    };    /**     * 开始预览。自动调用原生JavaScript实现相关元素的定位以及渲染。     */    this.preview = function () {        var file = document.getElementById(this.fileId);        var container = document.getElementById(this.containerId);        container.innerHTML = "";        /**         * 防止内部作用域覆盖问题。         * @type {ImgPrevirewer}         */        var that = this;        // HTML5 需要使用FileReader的相关API来读取本地数据。        if (window.FileReader) {            // 针对多个上传文件批量处理。            for (var index = 0, f; f = file.files[index]; index++) {                var filereader = new FileReader();                filereader.onload = function (event) {                    var srcpath = event.target.result;                    if (!that.validateImg(srcpath)) {                        console.log(this.tip);                    } else {                        that.showPreviewImg(srcpath);                    }                };                filereader.readAsDataURL(f);            }        } else {            // 低版本降级处理。            if (!/\.jpg$|\.png$|\.gif$/i.test(file.value)) {                console.log(this.tip);            } else {                that.showPreviewImg(file.value);            }        }    }    /**     * 根据图片的base64编码格式查看图片是否符合要求。     * @param data  编码后的图片数据。     * @returns {*}     */    this.validateImg = function (data) {        var pos = data.indexOf(",") + 1;        for (var e in this.filter) {            if (data.indexOf(this.filter[e]) === pos) {                return e;            }        }        return null;    }    /**     * 开始实现对图片的预览,根据this.imgStyle进行相关渲染操作。     * @param src     */    this.showPreviewImg = function (src) {        var img = document.createElement('img');        img.src = src;        img.style = this.imgStyle;        container.appendChild(img);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120

使用方式

下面来一个简单的“模板式”使用技巧。

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Test</title>    <script src="img-previewer.js"></script></head><body><input type="file" id="file" multiple onchange="preview()"><div id="container"></div><script>    function preview(){        var config = {            tip: "请上传格式为png, gif或者jpg的图片",            fileId: "file",            containerId: "container",            imgStyle: "width:320px;height:auto;border-radius:64%;"        }        var previewer = new ImgPrevirewer(config);        previewer.preview();    }</script></body></html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

测试

为了保证这个组件的稳定性,接下来来个简单的测试。

  • 首先是在Chrome浏览器上,发现可以正常工作。

测试组件稳定性

  • 接下来是在Edge浏览器上的测试。(发现样式不兼容) 
    Edge浏览器功能实现了,但是样式不够兼容

  • 不出所料,IE系的浏览器样式都没能兼容。 
    IE浏览器样式不兼容

。。。

最终发现,Chrome等WebKit内核的浏览器可以完美支持,对于微软系浏览器而言,功能可以满足,但是样式上不兼容,这点可以通过特定的浏览器头来实现,不再过多叙述。

总结

总的来说,关于图片上传时的预览功能,实用性还是很强的。对于一个网站可以算是一个加分项。当然了,该网站有一个设计感不错的美工或者前端,不像我做出的页面好难看(⊙﹏⊙)b。

大概就是这样咯,有需要的尽管拿去使用。