简体   繁体   中英

File upload using react + asp.net core 2 application not working

I am trying to do a file upload functionality, where my front end contains react and server is asp.net core 2 . I tried with various combinations but my code is not working.(Getting error at server end and most likely getting content-type error). Following is the snippets for both front end and server:

React Code is:

const formData: any = new FormData();<br />
formData.append("File",data[0]); // data[0] contains the file object<br/>
return axios.post(SAVE_ATTACHMENT_DATA, formData, 
    {headers: { 'Content-Type':'multipart/form-data' }}
  )
      .then(resp => {
        // 
      }, err => {
        // 
      })
  };

ASP.NET Core 2 Code is:

[HttpPost]
[Route("upload")]
public async Task<IActionResult> Upload()
{
    var files = Request.Form.Files; // getting error here in "Form"
    FileUploadViewModel model = new FileUploadViewModel(); // model been defined in another file
    var file = model.File;

     if (file.Length > 0)
     {
         string path = Path.Combine(@"temp\", "uploadFiles");
         using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
         {
             await file.CopyToAsync(fs);
         }

          model.source = $"/uploadFiles{file.FileName}";
          model.Extension = Path.GetExtension(file.FileName).Substring(1);
     }
            return BadRequest();
}

Can some one please help me with the same.

All you're doing in your action is newing up your model, which then, obviously isn't going to have any file uploads associated with it, because it was created manually by you and not from the post data. Instead, you should take your model as a param to your action, and then use that instance rather than creating your own:

[HttpPost]
[Route("upload")]
public async Task<IActionResult> Upload(FileUploadViewModel model)

It should work like this:

React Code

    const formData = new FormData();
    formData.append("file", data[0]);
    return axios.post(SAVE_ATTACHMENT_DATA, formData)

ASP.NET Core 2:

[HttpPost]
[Route("upload")]
public async Task<IActionResult> Upload(IFormFile file)
{

     if (file.Length > 0)
     {
         string path = Path.Combine(@"temp\", "uploadFiles");
         using (var fs = new FileStream(Path.Combine(path, file.FileName), FileMode.Create))
         {
             await file.CopyToAsync(fs);
         }

          model.source = $"/uploadFiles{file.FileName}";
          model.Extension = Path.GetExtension(file.FileName).Substring(1);
     }
     return BadRequest();
}

Important: The name of the file in React has to be the same as the parameter name in the .NET Core method or else the IFormFile will be null. For example formData.append('sameName', data[0]); in React and IFormFile sameName in .NET Core.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM