如何在React.js中上传和读取CSV文件?
问题描述:
我希望用户上传.csv文件,然后让浏览器能够解析该文件中的数据。我正在使用ReactJS。这怎么样?谢谢。
I would like the user to upload a .csv file, and then have the browser be able to parse the data from that file. I am using ReactJS. How would this work? Thanks.
答
想出来。 react-file-reader 和HTML5的FileReader的组合(参见这个页面)。
Figured it out. A combination of react-file-reader and HTML5's FileReader (see this page).
将react-file-reader位置于render中:
Placed the react-file-reader bit inside of render:
<ReactFileReader handleFiles={this.handleFiles} fileTypes={'.csv'}>
<button className='btn'>Upload</button>
</ReactFileReader>
然后再上面这个。
handleFiles = files => {
var reader = new FileReader();
reader.onload = function(e) {
// Use reader.result
alert(reader.result)
}
reader.readAsText(files[0]);
}