Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data and image both to "ASP.NET Core" Web API using Angular 2(typescript)?

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);
    }
like image 905
Ketankumar Godhani Avatar asked Jan 02 '17 11:01

Ketankumar Godhani


1 Answers

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();
}
like image 121
Lukasz Mk Avatar answered Nov 04 '22 21:11

Lukasz Mk