3

I have this client code on web-client to load some kind of file.

fileUploaded(files) {
  files.forEach(async ifile => {
    await axios.post('http://localhost:5000/api/upload', ifile)
      .then(res => {
        console.log(res)
      }).catch(err => {
        console.error(err); 
      });
  });
}

My endpoint code looks like this:

[HttpPost("upload")]
public async Task<IActionResult> UploadFile([FromBody] IFormFile file)
{
    var data = new byte[file.Length];

    using (var bstream = file.OpenReadStream())
    {
        while (bstream.CanRead)
        {
            bstream.Read(data);
        }
    }

    // etc

    return Ok();
}

Parameter file is always null. How to deliver this file from the client the right way?

1
  • try using [FromForm] instead of [FromBody] Commented Jun 5, 2021 at 22:17

2 Answers 2

6

Instead of

UploadFile([FromBody] IFormFile file)

Use

UploadFile([FromForm] IFormFile file)

And

fileUploaded(files) {
  files.forEach(async ifile => {
    const formData = new FormData();
    formData.append('file', ifile)
    await axios.post('http://localhost:5000/api/upload', formData)
      .then(res => {
        console.log(res)
      }).catch(err => {
         console.error(err); 
      });
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

what is fileUploaded? Is it a function?
It is a JavaScript function, @MatiasNovillo
1

in the UploadFile method, just, do this

//if asp.net mvc
var file1 = System.Web.HttpContext.Current.Request.Files[0];

//if asp.net core
var file2 = Request.Form.Files[0];

1 Comment

This is a valid alternative to changing the method signature

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.