9

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);
    }

2 Answers 2

5

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

I'm using <input type="file"/> control. Please advise How can I bind that base 64 to <img>?
Use Angular/JacaScript - just create a simple 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: msdn.microsoft.com/en-us/library/ms536912(v=vs.85).aspx
or you can use alternative way: <form enctype='multipart/form-data'> - I will update my answer.
@LukaszMakowej In case of solution 1, Consider there is a Product model which can have many Images, how can those models and their relations be realized? My original question here, I am trying to do exactly the same, it's just that for storing base64 string didn't work properly-it was chopping big string while saving so I read converting it to byte[] would solve the problem: stackoverflow.com/questions/43250261/…
As always there is more than one way to do things ;) Array/List of strings works well in my case (I'm using AngularJS + WebAPI Core) - perhaps it depends on configuration or it's Encoding issue? I'm sending/storing strings and I'm not converting it to byte[] at any point so I'm not sure if it will work well.
0

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);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.