3分钟教你用原生js实现具有进度监听的文件上传预览组件

简介: 本文主要介绍如何使用原生js,通过面向对象的方式实现一个文件上传预览的组件,该组件利用FileReader来实现文件在前端的解析,预览,读取进度等功能,并对外暴露相应api来实现用户自定义的需求,比如文件上传,进度监听,自定义样式,读取成功回调等。

本文主要介绍如何使用原生js,通过面向对象的方式实现一个文件上传预览的组件,该组件利用FileReader来实现文件在前端的解析,预览,读取进度等功能,并对外暴露相应api来实现用户自定义的需求,比如文件上传,进度监听,自定义样式,读取成功回调等。


组件设计架构如下:



涉及的核心知识点如下:


  1. 闭包:减少变量污染,缩短变量查找范围


  1. 自执行函数


  1. file API:对文件进行读取,解析,监控文件事件


  1. DocumentFragment API:主要用来优化dom操作


  1. minix :用来实现对象混合


  1. 正则表达式:匹配文件类型


  1. class :类组件


github地址


用原生js实现具有进度监听的文件上传预览组件


Demo演示






使用:


<div id="test"></div>
<script src="./js/xjFile.js"></script>
<script>
    new xjFile({
        el: '#test', // 不填则直接默认挂在body上
        accept: 'image/png', // 可选
        clsName: 'xj-wrap', // 可选
        beforeUpload: function(e) { console.log(e) }, // 可选
        onProgress: function(e) { console.log(e) }, // 可选
        onLoad: function(e) { console.log(e) }, // 可选
        onError: function(e) { console.error('文件读取错误', e) } // 可选
    });
</script>

css代码:

.xj-wrap {
            position: relative;
            display: inline-block;
            border: 1px dashed #888;
            width: 200px;
            height: 200px;
            border-radius: 6px;
            overflow: hidden;
        }
        .xj-wrap::before {
            content: '+';
            font-size: 36px;
            position: absolute;
            transform: translate(-50%, -50%);
            left: 50%;
            top: 50%;
            color: #ccc;
        }
        .xj-wrap .xj-pre-img {
            width: 100%;
            height: 100%;
            background-repeat: no-repeat;
            background-position: center center;
            background-size: 100%;
        }
        .xj-file {
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }

js代码:

(function(win, doc){
    function xjFile(opt) {
        var defaultOption = {
            el: doc.body,
            accept: '*', // 格式按照'image/jpg,image/gif'传
            clsName: 'xj-wrap',
            beforeUpload: function(e) { console.log(e) },
            onProgress: function(e) { console.log(e) },
            onLoad: function(e) { console.log(e) },
            onError: function(e) { console.error('文件读取错误', e) }
        };
        // 获取dom
        if(opt.el) {
            opt.el = typeof opt.el === 'object' ? opt.el : document.querySelector(opt.el);
        }
        this.opt = minix(defaultOption, opt);
        this.value = '';
        this.init();
    }
    xjFile.prototype.init = function() {
        this.render();
        this.watch();
    }
    xjFile.prototype.render = function() {
        var fragment = document.createDocumentFragment(),
            file = document.createElement('input'),
            imgBox = document.createElement('div');
        file.type = 'file';
        file.accept = this.opt.accept || '*';
        file.className = 'xj-file';
        imgBox.className = 'xj-pre-img';
        // 插入fragment
        fragment.appendChild(file);
        fragment.appendChild(imgBox);
        // 给包裹组件设置class
        this.opt.el.className = this.opt.clsName;
        this.opt.el.appendChild(fragment);
    }
    xjFile.prototype.watch = function() {
        var ipt = this.opt.el.querySelector('.xj-file');
        var _this = this;
        ipt.addEventListener('change', (e) => {
            var file = ipt.files[0];
            // 给组件赋值
            _this.value = file;
            var fileReader = new FileReader();
            // 读取文件开始时触发
            fileReader.onloadstart = function(e) {
                if(_this.opt.accept !== '*' && _this.opt.accept.indexOf(file.type.toLowerCase()) === -1) {
                    fileReader.abort();
                    _this.opt.beforeUpload(file, e);
                    console.error('文件格式有误', file.type.toLowerCase());
                }
            }
            // 读取完成触发的事件
            fileReader.onload = (e) => {
                var imgBox = this.opt.el.querySelector('.xj-pre-img');
                if(isImage(file.type)) {
                    imgBox.innerHTML = '';
                    imgBox.style.backgroundImage = 'url(' + fileReader.result + ')';
                } else {
                    imgBox.innerHTML = fileReader.result;
                }
                imgBox.title = file.name;
                this.opt.onLoad(e);
            }
            // 文件读取出错事件
            fileReader.onerror = (e) => {
                this.opt.onError(e);
            }
            // 文件读取进度事件
            fileReader.onprogress = (e) => {
                this.opt.onProgress(e);
            }
            isImage(file.type) ? fileReader.readAsDataURL(file) : fileReader.readAsText(file);
        }, false);
    }
    // 清除ipt和组件的值,支持链式调用
    xjFile.prototype.clearFile = function() {
        this.opt.el.querySelector('.xj-file').value = '';
        this.value = '';
        return this
    }
    // 简单对象混合
    function minix(source, target) {
        for(var key in target) {
            source[key] = target[key];
        }
        return source
    }
    // 检测图片类型
    function isImage(type) {
        var reg = /(image\/jpeg|image\/jpg|image\/gif|image\/png)/gi;
        return reg.test(type)
    }
    // 将方法挂载到window上
    win.xjFile = xjFile;
})(window, document);

class版(后期规划)


class版的也很简单,大致框架如下,感兴趣的朋友可以实现一下呦~

class XjFile {
    constructor(opt) {
    }
    init() {
    }
    watch() {
    }
    render() {
    }
    clearFile() {
    }
    minix(source, target) {
    }
    isImage(type) {
    }
}

总结


该组件仍有需要完善的地方,在后期使用中,会慢慢更新,优化,欢迎大家提出宝贵的建议。



目录
相关文章
|
17天前
|
JSON JavaScript 前端开发
JavaScript原生代码处理JSON的一些高频次方法合集
JavaScript原生代码处理JSON的一些高频次方法合集
|
1月前
|
JavaScript
Vue.js 修饰符:精准控制组件行为
Vue.js 修饰符:精准控制组件行为
|
2月前
|
JavaScript
原生js实现复选框(全选/全不选/反选)效果【含完整代码】
原生js实现复选框(全选/全不选/反选)效果【含完整代码】
58 1
|
2月前
|
JavaScript
JS实现百分比进度球
JS实现百分比进度球
29 1
|
17天前
|
JavaScript 算法
原生JS完成“一对一、一对多”矩形DIV碰撞检测、碰撞检查,通过计算接触面积(重叠覆盖面积)大小来判断接触对象DOM
原生JS完成“一对一、一对多”矩形DIV碰撞检测、碰撞检查,通过计算接触面积(重叠覆盖面积)大小来判断接触对象DOM
|
3月前
|
前端开发 JavaScript 索引
|
3天前
|
JavaScript 前端开发 UED
深入解析JavaScript原生操作DOM技术
【4月更文挑战第22天】本文深入探讨JavaScript原生DOM操作技术,包括使用`getElement*`方法和CSS选择器获取元素,借助`createElement`与`appendChild`动态创建及插入元素,修改元素内容、属性和样式,以及删除元素。通过掌握这些技术,开发者能实现页面动态交互,但应注意避免过度操作DOM以优化性能和用户体验。
|
17天前
|
JavaScript
【归总】原生js操作浏览器hash、url参数参数获取/修改方法合集
【归总】原生js操作浏览器hash、url参数参数获取/修改方法合集
N..
|
1月前
|
JavaScript 前端开发 测试技术
Vue.js的组件
Vue.js的组件
N..
14 1
N..
|
1月前
|
JavaScript 前端开发 数据处理
Vue.js的过滤器和监听属性
Vue.js的过滤器和监听属性
N..
19 1