前端JS读取文件内容并展示到页面上
2024-09-25
575
版权
版权声明:
本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《
阿里云开发者社区用户服务协议》和
《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写
侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
简介:
前端JavaScript使用FileReader API读取文件内容,支持文本类型文件。在文件读取成功后,可以通过onload事件处理函数获取文件内容,然后展示到页面上。
核心法宝:FileReader
{
this.returnDomFun(
<>
title={ 'AAAA'} fileName={ fileName} onChangeInput={ (e) => this.inputName(`fileName`, e.target.value)} onChange={ this.chengFileFun} beforeUpload={ this.beforeUpload} maxCount={ 1} action="#" showUploadList={ false} /> > , { width: "600px" }) } 我们只关注onChange事件即可, chengFileFun = (filer) => { let name = filer.file.name //文件对象 let fileObj = filer.file // 实例化FileReader对象 var reader = new FileReader(); // 正则校验 if (/text\/\w+/.test(fileObj.type)) { reader.readAsText(fileObj.originFileObj); // 读取失败自动触发 reader.onerror = function (event) { message.warning("文件读取失败") return false }; // 读取完成触发 reader.onload = function () { if (this.readyState === 2) { let result = this.result.split("\r\n") console.log(result, 'result') } } } this.setState({ fileName: name, fileObj }) }