Search code examples
reactjspostfile-uploadasp.net-coreinternal-server-error

Reactjs post multiple values including a file to ASP.Net Core controller action


I need to post string and file from ReactJS to ASP.Net Core 2.0 controller method and bump into 500 error and the request never hits the controller action method. Here is the ReactJS code:

    private submit(e) {
        e.preventDefault();
        let data = new FormData();
        let str = (document.getElementById('TweetString') as HTMLInputElement).value;
        let file = (document.getElementById('TweetFile') as HTMLInputElement).files[0];
        data.append("TweetString", str);
        data.append("File", file);
        fetch('/home/post', {
            method: "post",
            headers: { 'Content-Type': 'multipart/form-data' },
            body: data
        }).then(function (res) {
            if (res.ok) {
                console.log("Perfect! ");
            } else
                console.error("Post error: "+ res.status);
        }).catch(e => {
            console.log("error: " + e);
        });
    }

    <form id="frmTweet" encType="multipart/form-data">
        <div className="row">
            <div className="col-md-6">
                <input type="text" className="form-control" id="TweetString" placeholder="TweetString"></input>
             </div>
             <div className="col-md-6">
                 <input type="file" className="form-control" id="TweetFile" placeholder="Select file to upload..."></input>
             </div>
         </div>
         <div className="row">
             <button onClick={this.submit.bind(this)} className="button">Submit</button>
         </div>
     </form>

Here is my controller method signature:

    [HttpPost]
    public async Task<IActionResult> Post([FromForm]string TweetString, [FromForm]IFormFile File) {}

Any advice and insight is appreciated. Thanks.


Solution

  • Solution:

    Client: use axios

    Server: Use IFormCollection