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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Figured it out. A combination of react-file-reader and HTML5's FileReader (see this page).
Placed the react-file-reader bit inside of render:
<ReactFileReader handleFiles={this.handleFiles} fileTypes={'.csv'}>
<button className='btn'>Upload</button>
</ReactFileReader>
And then this above.
handleFiles = files => {
var reader = new FileReader();
reader.onload = function(e) {
// Use reader.result
alert(reader.result)
}
reader.readAsText(files[0]);
}
回答2:
I would use Papa Parse (https://www.npmjs.com/package/papaparse). And here is an example react component:
class FileReader extends React.Component {
constructor() {
super();
this.state = {
csvfile: undefined
};
this.updateData = this.updateData.bind(this);
}
handleChange = event => {
this.setState({
csvfile: event.target.files[0]
});
};
importCSV = () => {
const { csvfile } = this.state;
Papa.parse(csvfile, {
complete: this.updateData,
header: true
});
};
updateData(result) {
var data = result.data;
console.log(data);
}
render() {
console.log(this.state.csvfile);
return (
<div className="App">
<h2>Import CSV File!</h2>
<input
className="csv-input"
type="file"
ref={input => {
this.filesInput = input;
}}
name="file"
placeholder={null}
onChange={this.handleChange}
/>
<p />
<button onClick={this.importCSV}> Upload now!</button>
</div>
);
}
}
export default FileReader;