我正在尝试通过表单读取多个文件。战后我想将它们存储在一个CSV文件中。
当前状态下的数据为空,因为FileReader尚未完成读取,但是我似乎无法找出一个优雅的选择。有人可以帮忙吗?
到目前为止,我的代码:
class App extends Component {
constructor() {
super()
this.state = { data : null, files : null }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange = (event) => {
this.setState({
files: event.target.files
})
}
handleSubmit = (event) => {
event.preventDefault()
this.retrieveFiles()
this.exportToCSV()
}
retrieveFiles = () => {
this.setState({ data: [] })
Array.from(this.state.files).forEach(
(file) => {
var reader = new FileReader()
reader.filename = file.name
reader.onloadend = this.readFiles
reader.readAsText(file, "UTF-8")
}
)
}
readFiles = (event) => {
this.setState((state) => {
var parser = new DOMParser();
var data = state.data.concat([{
filename : event.target.filename,
content: parser.parseFromString(event.target.result, "text/xml")
}])
return { data : data }
})
}
exportToCSV = (data) => {
console.log(this.state.data)
}
render() {
return (
<div className="xbpm-tracer">
<form onSubmit={this.handleSubmit}>
<h1>Upload file(s)</h1>
<label>
<input type="file" name="file" onChange={this.handleChange} multiple />
</label>
<label>
<input type="submit" name="submit" value="Upload" />
</label>
</form>
</div>
)
}
}
export default App;