读取文件并解析其内容 [英] Read a file and parse its content

查看:30
本文介绍了读取文件并解析其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有文件上传控件,它保存选定的文件,如下所示,

<label id="lbl">文件 </label><input #fileInput type='file'/>

我有一个提交按钮,如下所示,

当我选择一个文件并单击上传按钮时,我需要该文件中的内容,而无需将其发送到服务器并从那里读取.

注意:文件类型为csv

解决方案

您可以在 javascript 中使用 FileReader 将其作为 csv 文件来实现

添加文件更改事件以将文件存储在如下对象中,

<label id="lbl">代码 </label><input type='file' (change)="fileChanged($event)">

该函数应该将文件设置为稍后使用的对象

file:any;文件更改(e){this.file = e.target.files[0];}

当点击提交按钮时,可以使用javascript中FileReaderreadAsText()方法得到如下内容,

uploadDocument(file) {让 fileReader = new FileReader();fileReader.onload = (e) =>{控制台日志(fileReader.result);}fileReader.readAsText(this.file);}

注意:onload 事件将在读取内容后触发,因此您的逻辑应在 onLoad 函数内.

I have file upload control which holds the selected file as below,

<div class="Block">
  <label id="lbl">File </label>
  <input #fileInput type='file'/>
</div>

I have a submit button as below,

<button type="button" class="btn btn-primary" 
     (click)="uploadDocument()">Upload File</button>

When I select a file and click on the upload button the file I need the contents inside the file without sending it to the server and reading from there.

Note: Type of file will be csv

解决方案

You can use FileReader in javascript to achieve this as its a csv file

Add a file change event to store the file in a object as below,

<div class="Block">
  <label id="lbl">Code </label>
  <input type='file' (change)="fileChanged($event)">

</div>

The function should set the file to an object which is used later

file:any;
fileChanged(e) {
    this.file = e.target.files[0];
}

When the submit button is clicked you can use the readAsText() method of FileReader in javascript to get the content as below,

uploadDocument(file) {
    let fileReader = new FileReader();
    fileReader.onload = (e) => {
      console.log(fileReader.result);
    }
    fileReader.readAsText(this.file);
}

Note: onload event will be fired after the content is read so your logic should be inside the onLoad function.

这篇关于读取文件并解析其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆