React 文件实现上传功能

2022-07-27,,,

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      imgUrl: '',
      file: null
    };

    // 为了在回调中使用 `this`,这个绑定是必不可少的
    this.fileChange = this.fileChange.bind(this);
    this.upload = this.upload.bind(this);
  }

  fileChange({target}) {
    console.log(target.files);
    console.log(target.files[0]);
    this.setState({
      file: target.files[0]
    });
  }

  upload() {
    console.log(this.state.file);
    const formData = new FormData();
    formData.append('file', this.state.file);
    formData.append('token', 'xxxxxxx');
    let app = this;
    axios.post('xxxx/supplier/public/qiniusave', formData).then(res => {
      console.log(res);
      app.setState({
        imgUrl: res.data.data
      });
    })
  }

  render() {
    return (
      <div>
        <h2>Home</h2>
        <input type="file" onChange={this.fileChange} multiple/>
        <button onClick={this.upload}>点击上传</button>
        <div>
          <img width={'45'} src={this.state.imgUrl} alt=""/>
        </div>
      </div>
    );
  }
}

本文地址:https://blog.csdn.net/u013239476/article/details/110247303

《React 文件实现上传功能.doc》

下载本文的Word格式文档,以方便收藏与打印。