Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive file and other form data together in ASP.NET Core Web API (boundary based request parsing)

How would you form your parameters for the action method which is supposed to receive one file and one text value from the request?

I tried this

public string Post([FromBody]string name, [FromBody]IFormFile imageFile)

And tried hitting it from Postman but it gives me 500 Internal Server Error. I also can't debug it because it never hits the first statement inside the action method where I've put my breakpoint.

Any idea how can we parse boundary based requests and extract file(s) and other textual field(s)? I am new to ASP.NET Core.

like image 394
shashwat Avatar asked Nov 16 '16 10:11

shashwat


2 Answers

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;
    
    // ...
}
like image 100
Ye Yint Avatar answered Nov 12 '22 02:11

Ye Yint


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"];
like image 32
Ali A. Aziz Avatar answered Nov 12 '22 04:11

Ali A. Aziz