1

I have some issues uploading file to my Web Api. I've created empty Web API Project and tried this code from some msdn page:

public class UploadController : ApiController
    {
        [HttpPost]
        [Route("api/upload/file")]
        public async Task<HttpResponseMessage> PostFormData()
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.
                foreach (MultipartFileData fileData in provider.FileData)
                {
                    Trace.WriteLine(fileData.Headers.ContentDisposition.FileName);//get FileName
                    Trace.WriteLine("Server file path: " + fileData.LocalFileName);//get File Path
                }
                return Request.CreateResponse(HttpStatusCode.OK, "pass upload file successed!");
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

    }

To make sure I don't make any mistake on the frontend part I am using postman: postman with form-data

However initially I need to post this file from react app, and my code looks like this:

const UploadFile = connect(
    mapStateToProps,
    mapDispatchToProps,
)(
    class extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                file: '',
            };
        }

        async submit(e) {
            e.preventDefault();
            const formData = new FormData();
            formData.append('file', this.state.file, { type: 'text/csv' });

            // I am dispatching redux action here, but to simplify tests with file upload I am using axios post right here
            // i tried different urls with and without action names
            post('http://localhost:44370/api/upload/file', formData)
                .catch(error => {
                    console.log(error);
                })
                .then(() => {});
        }
        setFile(e) {
            this.setState({ file: e.target.files[0] });
        }

        render() {
            return (
                <div className="container-fluid">
                    <form onSubmit={e => this.submit(e)}>
                        <div className="col-sm-12 btn btn-primary">
                            File Upload
                        </div>
                        <h1>File Upload</h1>
                        <input type="file" onChange={e => this.setFile(e)} />
                        <button className="btn btn-primary" type="submit">
                            Upload
                        </button>
                    </form>
                </div>
            );
        }
    },
);

But I was never able to reach a breakpoint on my action, neither from react app nor from the postman. I am always getting 404 not found via postman and ERR_CONNECTION_ABORTED from react app.

I also tried this solution and a lot of other different approaches from the internet, also tried using HttpFileBase, but still no result.

Any ideas about how to change the code to be able to upload a file to Web Api Controller's action?

PS. I was able to upload file to asp.net core controller with such code:

[HttpPost]
        public async Task<IActionResult> Post(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return Content("file not selected");

            var fileId = Guid.NewGuid();

            var path = Path.Combine(
                Directory.GetCurrentDirectory(), "uploads",
                file.FileName);

            using (var stream = new FileStream(path, FileMode.Create))
                await file.CopyToAsync(stream);
        }

and the same react code but I need a solution for not .net core project, just a regular asp.net web api.

UPDATE According to a comment, I tried html page with nothing but form:

<form
  name="form1"
  method="post"
  enctype="multipart/form-data"
  action="http://localhost:44370/api/upload/file"
>
  <div>
    <label for="file">File</label>
    <input name="file" type="file" />
  </div>
  <div>
    <input type="submit" value="Submit" />
  </div>
</form>

But I am getting 404 not found

4
  • I tested the controller on my environment and it is working as expected. I was able to upload a file by simply adding an HTML page with an <input type="file" /> and with a form ` enctype="multipart/form-data"` and action="/api/upload/file" to my web API project . So you say the react code is working and I say the controller code is working. Then you must have something wrong with the controller configuration or routing for example. Where did you put the controller class? I put it under the Controllers folder Commented Mar 30, 2020 at 0:59
  • @OguzOzgul yes, it's under controllers folder and I tried different routes configurations, also added [Route] attribute to be sure I didn't make a mistake on it. Is your html page just a regular html or something like .cshtml from mvc? Commented Mar 30, 2020 at 2:07
  • @OguzOzgul I tried html page again, but it's still 404, I updated question with code snippet and screenshot. Commented Mar 30, 2020 at 2:17
  • It is a regular HTML page, the very basics, exactly as yours, and it helped us solve the problem if I am not mistaken in my judgment. Commented Mar 30, 2020 at 7:13

1 Answer 1

2

Oh my.. Look at the error message in the screenshot.

it is not only 404, it is 404.13 - Content length too large.. Are you trying to upload a very huge file?

https://social.msdn.microsoft.com/Forums/ie/en-US/d3214048-67d2-4328-a34e-1459e629512a/http-file-upload-error-in-request-limit?forum=vsdebug

You should modify request filtering settings if you are going to allow uploading of files with enormous sizes.

Look at the "things you can try" section in the screenshot:

Verify the configuration/system.webServer/security/requestFiltering/requestLimits@maxAllowedContentLength setting in the applicationhost.config or web.config file

Sign up to request clarification or add additional context in comments.

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.