优秀的编程知识分享平台

网站首页 > 技术文章 正文

JavaScript fileReader对象(js filereader blob)

nanyue 2024-07-30 03:28:17 技术文章 10 ℃

HTML5之fileReader异步读取文件及文件切片读取

fileReader的方法与事件

fileReade实现图片预加载

fileReade实现文件读取进度条

fileReade的与file.s实现文件切片读取

一、fileReader的方法与事件

1.方法

FileReader.abort():终止读取操作。返回时, readyState属性为DONE。

FileReader.readAsArrayBuffer():将文件读取为ArrayBuffer数据对象。

FileReader.readAsBinaryString():将文件读取为二进制数据。

FileReader.readAsDataURL():将文件读取为DataURL编码(base64)==>URL格式的字符串。

FileReader.readAsText():将文件读取为文本==》字符串表示的文件内容。

2.事件

FileReader.onloadstart:读取开始时触发

FileReader.onprogress:读取中

FileReader.onloadend:读取完成触发, 无论成功或失败

FileReader.onload:文件读取成功完成时触发

FileReader.onabort:中断时触发

FileReader.onerror:出错时触发

3.实现图片读取预览

在Web FileReader API接口实现之前, 图片预览的通常做法是先将图片上传至服务器, 上传成功以后通过过触发ajax请求到刚刚上传的图片, 然后加载到页面。这个过程中如果图片选择错误或者需要修改上传的图片, 就需要重复上传和下载请求, 并且还需要在服务器替换图片资源, 会浪费大量的网络资源和服务器资源。现在通过FileReader实现本地图片读取预览, 就可以在本地实现图片修改, 节省服务器资源。

既然是HTML5的API就目前来说肯定存在兼容性问题, 目前IE10开始支持FileReader, 所以通过服务上传下载的图片预览方式还是有必要的, 接下来的示例仅仅展示FileReader的图片读取预览代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.imgBox{
display: flex;
width: 300px;
height: 300px;
border: 1px solid #300;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<input type="file" name="">
<div class="imgBox"></div>
</body>
<script>
var imgBox = document.getElementsByClassName('imgBox')[0];
var reader = new FileReader(); //创建文件读取对象
var inp = document.getElementsByTagName('input')[0]; //获取文件源
inp.onchange = function(){ //input域发生改变后触发文件读取
reader.readAsDataURL(inp.files[0]); //使用文件读取对象读取图片为base64编码
}
reader.onload = function(e){ //当图片读取成功后触发
var img = new Image(); //创建img对象
img.src = e.target.result; //给img对象添加缓存中的bese64位编码的图片数据(异步)
img.onload = function(e){ //图片数据加载完成以后
if(this.width > this.height){ //当图片的宽度大于高度
img.style.width = '100%'; //是:设置图片宽度100%,实现图片全部预览
}else{
img.style.height = '100%';//否:设置图片高度100%,实现图片全部预览
}
imgBox.style.backgroundColor = '#000';
imgBox.innerHTML = null;
imgBox.appendChild(img);
}
}
</script>
</html>

4.实现文件加载进度条

在FileReader.onprogress事件对象中有两个属性loaded和total, loaded表示当前文件读取大小, total表示文件整体大小, 并且在读取时会持续触发更新最新读取状态的数据,

根据FileReader.onprogress事件就可以实现文件加载进度条的动画效果了, 但是由于FileReader是h5的API在IE中最低兼容到10版本, 所以需要根据具体的项目和兼容性来设计交互。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.progress{
position: relative;
margin-top: 5px;
width: 300px;
height: 20px;
border: 1px solid #300;
}
.progressText{
display: inline-block;
position: absolute;
width: 300px;
height: 20px;
text-align: center;
font-size: 10px;
line-height: 20px;
}
.progressSpan{
display: inline-block;
/* width: 200px; */
height: 20px;
background-color: #f0f;
}
</style>
</head>
<body>
<input type="file" name="">
<!-- 文件加载进度条 -->
<div class="progress">
<span class="progressText"></span>
<span class="progressSpan"></span>
</div>
</body>
<script>
//获取文件源(所有功能实现的公共代码区)
var inp = document.getElementsByTagName('input')[0]; //获取文件源
var reader = new FileReader(); //创建文件读取对象
// fileReader实现图片加载进度条
var progressSpanObj = document.getElementsByClassName('progressSpan')[0];
var progressTextObj = document.getElementsByClassName('progressText')[0];
inp.onchange = function(){
reader.readAsArrayBuffer(inp.files[0]);
}
reader.onloadstart = function(e){ //开始读取文件时触发
progressTextObj.innerText = "正在读取文件(0%)...";
}
reader.onprogress = function(e){ //读取进度事件
console.log(Math.round(e.loaded / e.total * 100));
var precent = Math.round(e.loaded / e.total * 100);
progressSpanObj.style.width = precent / 100 * 300 + 'px';
progressTextObj.innerText = '正在读取文件(' + precent + '%)...';
}
reader.onload = function(e){
progressTextObj.innerText = '文件读取完成(100%)';
}
reader.onerror = function(e){
progressTextObj.innerText = "文件读取出错误(~0v0~)";
}
</script>
</html>

二、fileReade的与file.slice实现文件切片读取

通过input-type[file]获取的文件对象上有这样几个数据:

inputDom.files[0];//获取File对象(在onchange事件后获取)

File对象上的属性与方法:

File():构造函数,返回一个新的文件对象

File.lastModified:返回所引用文件最后的修改日期,为自 1970年1月1日0:00 以来的毫秒数。没有已知的最后修改时间则会返回当前时间。

File.lastModifiedDate:返回当前File对象所引用文件最后修改事件的Date都西昂。

File.name:返回当前File对象所引用文件的名字。

File.size:返回文件的大小

File.webkitRelativePath:返回Filex相关的path或URL(这是个非标准属性, chrome上获取的是一个空字符串)

File.slice():文件对象上本身是没有方法的,slice方法同通过继承Blob对象上的slice方法实现的。

File对象说明手册(MDN):https://developer.mozilla.org/zh-CN/docs/Web/API/File

File.slice()方法说明手册(MDN):https://developer.mozilla.org/zh-CN/docs/Web/API/Blob/slice

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
.progress{
position: relative;
margin-top: 5px;
width: 300px;
height: 20px;
border: 1px solid #300;
}
.progressText{
display: inline-block;
position: absolute;
width: 300px;
height: 20px;
text-align: center;
font-size: 10px;
line-height: 20px;
}
.progressSpan{
display: inline-block;
/* width: 200px; */
height: 20px;
background-color: #f0f;
}
</style>
</head>
<body>
<!--样式同上面的进度条实例一样,这里就不添加了-->
<input type="file" name="">
<!-- 文件加载进度条 -->
<div class="progress">
<span class="progressText"></span>
<span class="progressSpan"></span>
</div>
</body>
<script>
//获取文件源(所有功能实现的公共代码区)
var inp = document.getElementsByTagName('input')[0]; //获取文件源
var reader = new FileReader(); //创建文件读取对象
// fileReader实现图片加载进度条
var progressSpanObj = document.getElementsByClassName('progressSpan')[0];
var progressTextObj = document.getElementsByClassName('progressText')[0];
//file.slice(起始字节,终止字节)与FileReader实现文件切片读取
function PartFileReader(files,type,event){
this.files = files;//inputObj.files[0]
this.type = type; //配置FileReader读取文件的方法
this.event = event;//配置读取文件时需要触发的事件
this.total = files.size;//获取文件大小
this.step = 1024 * 1024;//1MB(单片大小/一兆)
this.loaded = 0; //文件当前读取进度
this.reader = new FileReader(); //实际读取文件的FileReader对象实例
this.abort = this.reader.abort; //中断文件读取(可以通过中断文件读取事件保留切片数据,实现下一次可以在原读取位置继续开始读取)
this.readPartFile(this.loaded); //开启读取文件
this.bindEvent();//绑定FileReader文件读取
}
//给切片读取对象原型上添加FileReader获取读取类型,开启读取文件
PartFileReader.prototype.readPartFile = function(start){
if(this.files.slice){
var file = this.files.slice(start,this.loaded + this.step);
switch(this.type){
case 'readAsBinaryString' :
this.reader.readAsBinaryString(file);
break;
case 'readAsDataURL' :
this.reader.readAsDataURL(file);
break;
case 'readAsArrayBuffer' :
this.reader.readAsArrayBuffer(file);
break;
case 'readAsText' :
this.readAsText(file);
break;
}
}
}
//给切片读取对象原型上绑定FileReader对象事件
PartFileReader.prototype.bindEvent = function(){
var self = this;
this.reader.onloadstart = function(e){
self.event.loadStart && self.event.loadStart.call(this,e);
}
this.reader.onprogress = function(e){
self.event.progress && self.event.progress.call(this,e);
}
this.reader.onload = function(e){
// 切片读取文件有别于非切片读取,切片读取的文件读取状态需要在每个切片读取成功后再刷新读取进度
self.loaded += e.loaded;
self.event.load && self.event.load.call(this,e,self.loaded,self.total);
if(self.loaded < self.total){
self.readPartFile(self.loaded);
}
}
this.reader.onloadend = function(e){
self.event.loadend && self.event.loadend.call(this,e);
}
this.reader.onabort = function(e){
self.event.abort && self.event.abort.call(this,e);
}
}
//调用文件切片读取对象,配置FileReader事件函数
inp.onchange = function(){
var reader = new PartFileReader(inp.files[0],'readAsArrayBuffer',{
loadStart:function(e){
progressTextObj.innerText = "正在读取文件(0%)...";
},
progress:function(e){},
load:function(e,loaded,total){
// 如果在读取的基础上写上传的话在这里获取读取成功的文件切片
// e.target.result //当前文件切片的数据
// (但是千万别在这里直接写网络请求,本地读取的速度远远大于网络请求,直接请求一个文件就会在瞬间发起大量请求)
// (最好的处理方式是将切片数据写入一个有序列表中,然后通过控制网络请求数量来实现)
var precent = Math.round(loaded / total * 100);
progressSpanObj.style.width = precent / 100 * 300 + 'px';
if(precent < 100){
progressTextObj.innerText = '正在读取文件(' + precent + '%)...';
}else if(precent == 100){
progressTextObj.innerText = '文件读取完成(100%)';
}
},
loadend:function(e){},
abort:function(e){},
error:function(e){
progressTextObj.innerText = "文件读取出错误(~0v0~)";
}
})
}
</script>
</html>
最近发表
标签列表