无法在 React js webapi MVC 中上传文件

Can not upload file in React js webapi MVC

我正在努力在 React js Web 中上传文件 api C# Mvc。在提交过程中,显示​​了以下错误消息的按钮。

"Uncaught (in promise) TypeError: Cannot read property 'state' of undefined"

控制器

 [Route("Api/Authenticate/Uploadfile")]
    [HttpPost]
    public void CreateImage([FromBody] UserPostModel model)
    {
        var file = model.File;
    }

反应组件:

import React, { PropTypes } from 'react';
import axios from 'axios';
class Dashboard extends React.Component {

    constructor(props){
        var files;
        super(props);
        this.state =  {
            selectedFile: null
}
}
fileChangedHandler = event => {
        this.setState({
            selectedFile: event.target.files[0]
          })
          var file = this.refs.file.files[0].name;
          let reader = new FileReader();
        reader.onloadend = () => {
        this.setState({
            imagePreviewUrl: reader.result
        });
        }

         reader.readAsDataURL(event.target.files[0])
    }
async Submit(e){
      e.preventDefault();
      console.log(this.state.selectedFile);
      await this.addImage(this.state.selectedFile);
    };

    addImage = async (image) => {
      await fetch('http://localhost:32188/Api/Authenticate/Uploadfile',
          {
              method: 'POST',
              mode: 'cors',
              headers: {
                  'Accept': 'application/json'
              },
              body: this.state.selectedFile
          }
      )
  }

 render() {

<form >
                                      <input   ref="file"   type="file"   name="user[image]"  onChange={this.fileChangedHandler}    style={{padding: '5px', marginLeft: '31px'}} />



                                      <div className="signin_form_button">
                                            <input type="submit" value="Upload" onClick={this.Submit} className="signin_form_buttonstyle" />
                                        </div>
                                   </form>
}

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

您需要在组件的构造函数中将异步 Submit(e) 函数与 'this' 绑定。 像 this.Submit.bind(this)

或者你应该用下面的方式定义它

    async Submit=(e)=> {
           //yout code here
        }

修改表单提交没问题

 <form onSubmit={e => this.submit(e)}>
                                  <input   ref="file"   type="file"   name="user[image]"  onChange={this.fileChangedHandler}    style={{padding: '5px', marginLeft: '31px'}} />   
        <div className="signin_form_button">
          <input type="submit" value="Upload"  className="signin_form_buttonstyle" />
        </div>

并删除按钮 onclick