教你3分鐘利用原生js實(shí)現(xiàn)有進(jìn)度監(jiān)聽的文件上傳預(yù)覽組件
前言
本文主要介紹如何使用原生js,通過面向?qū)ο蟮姆绞綄?shí)現(xiàn)一個(gè)文件上傳預(yù)覽的組件,該組件利用FileReader來實(shí)現(xiàn)文件在前端的解析,預(yù)覽,讀取進(jìn)度等功能,并對外暴露相應(yīng)api來實(shí)現(xiàn)用戶自定義的需求,比如文件上傳,進(jìn)度監(jiān)聽,自定義樣式,讀取成功回調(diào)等。
組件設(shè)計(jì)架構(gòu)如下:

涉及的核心知識(shí)點(diǎn)如下:
- 閉包:減少變量污染,縮短變量查找范圍
- 自執(zhí)行函數(shù)
- file API:對文件進(jìn)行讀取,解析,監(jiān)控文件事件
- DocumentFragment API:主要用來優(yōu)化dom操作
- minix :用來實(shí)現(xiàn)對象混合
- 正則表達(dá)式:匹配文件類型
- class :類組件
github地址
用原生js實(shí)現(xiàn)具有進(jìn)度監(jiān)聽的文件上傳預(yù)覽組件 (本地下載)
Demo演示




使用:
<div id="test"></div>
<script src="./js/xjFile.js"></script>
<script>
new xjFile({
el: '#test', // 不填則直接默認(rèn)掛在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('文件讀取錯(cuò)誤', 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('文件讀取錯(cuò)誤', 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);
// 給包裹組件設(shè)置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();
// 讀取文件開始時(shí)觸發(fā)
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());
}
}
// 讀取完成觸發(fā)的事件
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);
}
// 文件讀取出錯(cuò)事件
fileReader.onerror = (e) => {
this.opt.onError(e);
}
// 文件讀取進(jìn)度事件
fileReader.onprogress = (e) => {
this.opt.onProgress(e);
}
isImage(file.type) ? fileReader.readAsDataURL(file) : fileReader.readAsText(file);
}, false);
}
// 清除ipt和組件的值,支持鏈?zhǔn)秸{(diào)用
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版(后期規(guī)劃)
class版的也很簡單,大致框架如下,感興趣的朋友可以實(shí)現(xiàn)一下呦~
class XjFile {
constructor(opt) {
}
init() {
}
watch() {
}
render() {
}
clearFile() {
}
minix(source, target) {
}
isImage(type) {
}
}
總結(jié)
該組件仍有需要完善的地方,在后期使用中,會(huì)慢慢更新,優(yōu)化,歡迎大家提出寶貴的建議。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。
相關(guān)文章
使用Object.defineProperty實(shí)現(xiàn)簡單的js雙向綁定
這篇文章主要介紹了使用Object.defineProperty實(shí)現(xiàn)簡單的js雙向綁定的相關(guān)資料,需要的朋友可以參考下2016-04-04
JS開發(fā)中基本數(shù)據(jù)類型具體有哪幾種
JS的數(shù)據(jù)類型包括基本數(shù)據(jù)類型、復(fù)雜數(shù)據(jù)類型和特殊數(shù)據(jù)類型,今天我們主要先講解一下基本數(shù)據(jù)類型。感興趣的朋友一起看看吧2017-10-10
JavaScript實(shí)現(xiàn)簡單計(jì)算器小程序
這篇文章主要為大家詳細(xì)介紹了JavaScript實(shí)現(xiàn)簡單計(jì)算器小程序,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
event.X和event.clientX的區(qū)別分析
解釋一下event.X和event.clientX有什么區(qū)別?event.clientX返回事件發(fā)生時(shí),mouse相對于客戶窗口的X坐標(biāo) event.X也一樣但是如果設(shè)置事件對象的定位屬性值為relative2011-10-10
微信小程序?qū)崿F(xiàn)音頻文件播放進(jìn)度的實(shí)例代碼
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)音頻文件播放進(jìn)度的實(shí)例代碼,代碼包括對進(jìn)度條的實(shí)現(xiàn)及進(jìn)度條的滑動(dòng),對大家的工作或?qū)W習(xí)具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-03-03
JavaScript 判斷指定字符串是否為有效數(shù)字
最近在做一個(gè)ColdFusion的項(xiàng)目,有一個(gè)業(yè)務(wù)Check,需要用JavaScript實(shí)現(xiàn):判斷指定字符串是否為有效數(shù)字。2010-05-05

