Receive file and other form data together in ASP.NET Core Web API (boundary based request parsing)
I had the similar issue and I solved the problem by using [FromForm]
attribute and FileUploadModelView
in the function as follow:
[HttpPost][Route("upload")]public async Task<IActionResult> Upload([FromForm] FileUploadViewModel model, [FromForm] string member_code){ var file = model.File; // ...}
This is a quick solution for anyone who is facing the same issue:
You will use ajax to send the following formData
let formData: FormData;formData = new FormData();formData.append('imageFile', imageFile);formData.append('name', name);
Then you will receive it in your controller like this:
public string Post(IFormCollection data, IFormFile imageFile)
Then you will access the data as you do normally:
var name = data["name"];
In HomeController.cs
using Microsoft.AspNetCore.Hosting;.......private IHostingEnvironment _environment;public HomeController(IHostingEnvironment environment){ _environment = environment;}[HttpPost][ValidateAntiForgeryToken] public IActionResult Index(IFormCollection formdata){ var files = HttpContext.Request.Form.Files; foreach (var file in files) { var uploads = Path.Combine(_environment.WebRootPath, "Images"); if (file.Length > 0) { string FileName = Guid.NewGuid(); // Give file name using (var fileStream = new FileStream(Path.Combine(uploads, FileName), FileMode.Create)) { file.CopyToAsync(fileStream); } } }}
In view - Index.cshtml
<form method="post" enctype="multipart/form-data" > .....</form>
You can try this code.
Thanks!!