Angular-读取文件并解析其内容 [英] Angular - Read a file and parse its content
问题描述
我具有文件上传控件,该控件可按如下方式保存所选文件,
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.
注意:文件类型为csv
推荐答案
您可以在javascript中使用FileReader
作为其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];
}
单击提交按钮后,您可以在javascript中使用FileReader
的readAsText()
方法来获取如下内容,
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);
}
注意:读取内容后将触发onload
事件,因此您的逻辑应放在onLoad
函数中.
Note: onload
event will be fired after the content is read so your logic should be inside the onLoad
function.
这篇关于Angular-读取文件并解析其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!