0

我在反应中创建了一个小功能,其中我能够成功上传文件并将其保存在一个状态中。我正在尝试使用“fs-extra”npm 库解析文件内容并将其打印在控制台上。但是,我无法成功地做到这一点。下面是代码:

import * as fs from "fs-extra";
import axios from "axios";
export default class FileUpload extends React.Component<{}, { selectedFile: any, loaded: number }> {

constructor(props: any) {
    super(props);
    this.state = {
        selectedFile: null,
        loaded: 0
    }
}

changeHandler = (event: any) => {
    event.preventDefault();
    this.setState({
        selectedFile: event.target.files,
        loaded: 0
    })
}

clickHandler = async (event: any) => {
    event.preventDefault();
    const data = new FormData();
    for (let x = 0; x < this.state.selectedFile.length; x++) {
        console.log(fs.readFileSync(this.state.selectedFile[x], "utf-8"))
        data.append('file', this.state.selectedFile[x])
    }
    axios.post("http://localhost:8080/test", data, {

    }).then(res => {
        console.log(res.statusText)
    });
}
render() {
    return (
        <div className="container-fluid bg-secondary">
            <div className="row">
                <div className="col-md-6">
                    <form>
                        <div className="form-group">
                            <label htmlFor="exampleFormControlFile1">Example file input</label>
                            <input
                                multiple
                                onChange={this.changeHandler}
                                type="file"
                                className="form-control-file"
                                id="exampleFormControlFile1" />
                            <button
                                type="button"
                                className="btn btn-success btn-block"
                                onClick={this.clickHandler}
                            >Upload</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
}
}

我收到以下错误:

TypeError: Cannot read property 'native' of undefined

这段代码有什么问题?另外,我怎样才能达到我想要达到的目标?

4

0 回答 0