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
:Backend:
Your property in the model should have type
IFormFile
, then you can save the file on the server:Just set your model and POST/PUT it via webapi as you are used to do. I assume you have a web-api model object providing attributes for structured data and the image. usually a varbinary(max) in sql server.
In the snippet below I do what you are asking for with the "newattachment" object, which is actually a webapi-model.
For getting a new empty attachment-object I do a GET first against the webapi-Model used to store the images. In the next step I set the properties of this model including the image data itself ( a base64 encoded) string. Finally I do PUT/POST do save the object in the database) Client Side: Angular 2
Server Side (C#, Web API):