1

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.

2 Answers 2

2

Thanks for your post, this worked for me and I'd like to share an example for future reference.

To use axios with react you'll need the following npm packages: react, axios, prop-types, react-axios

I've got this React code on client side:

import React, { Component } from 'react';
import { post } from 'axios';

export class FileUpload extends Component {
    static displayName = FileUpload.name;

    async handleSubmit(e) {
        e.preventDefault();

        const url = 'api/Books';

        const formData = new FormData();
        formData.append('file', this.refs.File.files[0]);

        var book = {
            title: this.refs.Title.value,
            author: this.refs.Author.value,
            language: this.refs.Language.value
        };
        formData.append('metadata', JSON.stringify(book));

        post(url, formData);
    }

    render() {
        return (
            <div>
                <h1>File Upload</h1>
                <form onSubmit={e => this.handleSubmit(e)}>
                    <div className="form-group">
                        <label>Title</label>
                        <input className="form-control" ref="Title" required />
                    </div>
                    <div className="form-group">
                        <label>Author</label>
                        <input className="form-control" ref="Author" required />
                    </div>
                    <div className="form-group">
                        <label>Language</label>
                        <select className="form-control" ref="Language">
                            <option>English</option>
                            <option>German</option>
                            <option>French</option>
                        </select>
                    </div>
                    <div className="form-group">
                        <label>File</label>
                        <input type="file" className="form-control-file" ref="File" required />
                    </div>
                    <button type="submit" className="btn btn-primary">Submit</button>
                </form>
            </div>
        );
    }
}

and the following C# code in the .NET Core Web API 2 backend:

        [HttpPost]
        public void PostBook(IFormCollection bookData)
        {
            var book = JsonConvert.DeserializeObject<Book>(bookData["metadata"]);

            _bookService.AddBookToDb(book, bookData.Files[0]);
        }
Sign up to request clarification or add additional context in comments.

Comments

0

Solution:

Client: use axios

Server: Use IFormCollection

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.