I have code that can pass data only to web API but i want to pass data and Image both in same request not in different request using angular 2 + typescript and in ASP.Net Core Web API.
My Code to pass data to API:
Angular Code:
create(user) {
return this.authHttp.post(this._baseUrl + 'user/', JSON.stringify(userData)).map((res: Response) => {
return res;
}).catch(this.configService.handleError);
}
API Code:
[HttpPost]
public IActionResult Create([FromBody]UserModel user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//save user
_userRepository.Add(user);
_userRepository.Commit();
return new OkObjectResult(user.UserId);
}
Solution 1:
The simplest way is sending the image as a base64 string.
Just create a simple JavaScript function to read the file and convert it to base64 string. Do it before sending the file - probably onchange event on the <input>
will do the job for you.
Then you can store it directly in DB (or save as a file on the server if you need).
Image stored as base64 string can be send back and displaed directly by browser without additional actions, for example:
<img src="data:image/bmp;base64,[base64EncodedImageHere]" />
Solution 2:
Frontend:
If you are using HTML5 and a file upload control, just set form encoding as multipart/form-data
:
<form method="post" enctype="multipart/form-data">
Backend:
Your property in the model should have type IFormFile
, then you can save the file on the server:
IFormFile file;
using (var fileStream = File.Create( [file path here] ))
{
await file.CopyToAsync(fileStream);
await fileStream.FlushAsync();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With