简体   繁体   English

读取文件并解析其内容

[英]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.当我 select 一个文件并单击上传按钮时,我需要文件中的内容而不将其发送到服务器并从那里读取。

Note: Type of file will be csv注意:文件类型将为csv

You can use FileReader in javascript to achieve this as its a csv file您可以在 javascript 中使用FileReader将其作为csv文件来实现

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,当提交按钮被点击时,您可以使用 javascript 中FileReaderreadAsText()方法来获取如下内容,

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.注意:在读取内容后将触发onload事件,因此您的逻辑应该在onLoad函数内。

you pull the file out of the input and use the FileReader API您将文件从输入中拉出并使用 FileReader API

readFile(file: File) {
    var reader = new FileReader();
    reader.onload = () => {
        console.log(reader.result);
    };
    reader.readAsText(file);
}

if you want to make it as function you can do如果你想让它成为你可以做的功能

    readFileContent(file: File): Promise<string> {
        return new Promise<string>((resolve, reject) => {
            if (!file) {
                resolve('');
            }

            const reader = new FileReader();

            reader.onload = (e) => {
                const text = reader.result.toString();
                resolve(text);

            };

            reader.readAsText(file);
        });
    }

then然后

const fileContent = await readFileContent(file);

For those asking how to get string data after reading it, the data is in the result property of fileReader .对于那些询问如何在读取后获取字符串数据的人,数据在fileReaderresult属性中。 Check the code sample below.检查下面的代码示例。

    let fileString:any= "";

    uploadDocument(file) {
        let fileReader = new FileReader();
        fileReader.onloadend = (e) => {
           //console.log(myReader.result);
           // Entire file
           console.log(myReader.result);

           // By lines
           var lines = myReader.result.split('\n');
           for(var line = 0; line < lines.length; line++){
               console.log(lines[line]);
           }

           this.fileString = myReader.result;
        };

        fileReader.readAsText(this.file);
    }  

it works, try like this..它有效,试试这样..

var reader = new FileReader();
        reader.onloadend =(e) =>{
          var result = reader.result; 
              console.log(i+'/'+result)
              this.file64.push(result)
        };  
        reader.readAsDataURL(file);

There's a modern native alternative: File implements Blob , so we can call Blob.text().有一个现代的原生替代方案: File实现Blob ,因此我们可以调用 Blob.text()。

async function readText(event) {
  const file = event.target.files.item(0)
  const text = await file.text();
  
  document.getElementById("output").innerText = text
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Ionic (Angular) - 读取文件并解析其内容 - Ionic (Angular) - Read a file and parse its content 使用 *ngIf 读取其内容的数组? - Using *ngIf to read out an array on its content? Symfony 4 / Angular 8:读取嵌套的JSON并用其内容填充对象 - Symfony 4 / angular 8 : read nested JSON and fill object with its content Angular 4:如何使用 HTTPClient 读取文本文件的内容 - Angular 4: How to read content of text file with HTTPClient 如何读取angular中上传文件的内容? - How to read the content of an uploaded file in angular? 如何读取和解析 Vert.x 文件系统中的.xlsx 文件 - How to Read and Parse .xlsx file in Vert.x File System TypeScript 声明文件在其文件夹位于 typeRoots 时未读取 - TypeScript Declaration File not read while its folder is in typeRoots 从 API 读取文件及其属性并在 Angular 客户端下载 - Read file and its properties from API and download it in Angular Client Angular:如何从后端加载 svg 文件并将其内容用作模板? - Angular: how to load a svg file from a backend and use its content as a template? 如何在控制器文件中读取硬编码的json数据并显示其值 - How to read the hard coded json data in controller file and display its value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM