通过文件选择器完成
<input type="file" id="fileInput"> or 多选 <input type="file" id="fileInput" multiple>
可以通过change事件来监听文件的选择,也可以添加另一个UI元素让用户显式地开始对所选文件的处理
input file 具有一个files属性,该属性是File对象的列表(可能有多个选择的文件)
<script> document.getElementById('fileInput').addEventListener('change', function selectedFileChanged() { console.log(this.files); // will contain information about the file that was selected. }); </script>
File对象如下所示:
{ name: 'test.txt', // 所选文件的名称 size: 1024, // 字节大小 type: 'text/plain', // 基于文件扩展名的假定文件类型,这有可能是不正确的 lastModified: 1234567890, // 根据用户系统的最新更改的时间戳 lastModifiedDate: // 最后修改的时间戳的日期对象 }
读取文件,主要使用的是FileReader类。
该对象拥有的属性:
FileReader.error :只读,一个DOMException,表示在读取文件时发生的错误 。
FileReader.readyState:只读 表示FileReader状态的数字。取值如下:
FileReader.result:只读,文件的内容。该属性仅在读取操作完成后才有效,数据的格式取决于使用哪个方法来启动读取操作。
该对象拥有的方法:
readAsText(file, encoding):以纯文本形式读取文件,读取到的文本保存在result属性中。第二个参数代表编码格式。
readAsDataUrl(file):读取文件并且将文件以数据URI的形式保存在result属性中。
readAsBinaryString(file):读取文件并且把文件以字符串保存在result属性中。
readAsArrayBuffer(file):读取文件并且将一个包含文件内容的ArrayBuffer保存咋result属性中。
FileReader.abort():中止读取操作。在返回时,readyState属性为DONE。
文件读取的过程是异步操作,在这个过程中提供了三个事件:progress、error、load事件。
progress:每隔50ms左右,会触发一次progress事件。
error:在无法读取到文件信息的条件下触发。
load:在成功加载后就会触发。
例一:读取文本文件
document.getElementById('fileInput').addEventListener('change', function selectedFileChanged() {
if (this.files.length === 0) {
console.log('请选择文件!');
return;
}
const reader = new FileReader();
reader.onload = function fileReadCompleted() {
// 当读取完成时,内容只在`reader.result`中
console.log(reader.result);
};
reader.readAsText(this.files[0]);
});
首先,我们要确保有一个可以读取的文件。如果用户取消或以其他方式关闭文件选择对话框而不选择文件,我们就没有什么要读取和退出函数。
然后我们继续创建一个FileReader。reader的工作是异步的,以避免阻塞主线程和UI更新,这在读取大文件(如视频)时非常重要。
reader发出一个'load'事件(例如,类似于Image对象),告诉我们的文件已经读取完毕。
reader将文件内容保存在其result属性中。此属性中的数据取决于我们使用的读取文件的方法。在我们的示例中,我们使用readAsText方法读取文件,因此result将是一个文本字符串。
例二:显示本地选择的图片
如果我们想要显示图像,将文件读取为字符串并不是很有用。FileReader有一个readAsDataURL方法,可以将文件读入一个编码的字符串,该字符串可以用作<img>元素的源。本例的代码与前面的代码基本相同,区别是我们使用readAsDataURL读取文件并将结果显示为图像:
document.getElementById('fileInput').addEventListener('change', function selectedFileChanged() {
if (this.files.length === 0) {
console.log('No file selected.');
return;
}
const reader = new FileReader();
reader.onload = function fileReadCompleted() {
const img = new Image();
img.src = reader.result;
document.body.appendChild(img);
};
reader.readAsDataURL(this.files[0]);
});
使用element UI el-upload 读取本地文件
<el-upload class="upload-demo" :auto-upload="false" :on-change="openFile"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传txt文件,且不超过500kb</div> </el-upload>
JS实现
openFile(file) { var reader = new FileReader(); reader.onload = function () { if (reader.result) { //打印文件内容 console.log(reader.result); } }; reader.readAsText(file.raw); }
浙公网安备 33010602011771号