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();
}
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
this.dataService.getRecord('MT_DOKUMENTATION', -1)
.subscribe((data: any[]) => {
if (data) {
var newattachment: any = data;
newattachment.dokumentation = this.attachmentdata.split("base64,")[1];
this.dataService.saveRecord('MT_DOKUMENTATION', "id", newattachment)
.subscribe((data: any[]) => {
var newrec: any = data;
...
},
error => {
console.log(error);
},
() => {
console.log('Image Save complete')
});
});
Server Side (C#, Web API):
// PUT: api/MT_DOKUMENTATION/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutMT_DOKUMENTATION(int id, MT_DOKUMENTATION mT_DOKUMENTATION)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Entry(mT_DOKUMENTATION).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
...
}
return Ok(mT_DOKUMENTATION);
}