欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

React 文件实现上传功能

程序员文章站 2022-06-17 08:18:22
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.bi...
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