2

I have to create a Web API (I'm using ASP.NET Core 1.1), and one of the things it needs to be able to do is to receive a JPEG image (and later also other document types such as PDF).

The front end developer (using Angular2) said he will send the image to the API in Base64. I had previously created a controller action in my API that accepts an IFormFile, but the front end developer said he doesn't know how to send the API in this way.

So I now need to modify my API to accept a Base64 image. Can I have a simple controller action in the API which reads the body of the POST request, and then converts that into a file?

So:

    // POST: api/images
    [HttpPost]
    public async Task<IActionResult> PostImage([FromBody] string image)
    {
        byte[] bytes = Convert.FromBase64String(image);

        using (MemoryStream ms = new MemoryStream(bytes))
            Image image = Image.FromStream(ms);

        return CreatedAtAction("PostImage", new { id =  123});
    }

Should that do the trick?

haldo
  • 14,512
  • 5
  • 46
  • 52
Fabricio Rodriguez
  • 3,769
  • 11
  • 48
  • 101
  • base64 is a string representation of the image. you parameter needs to be a string. – Nkosi Jul 24 '17 at 10:46
  • Oh sorry, I actually knew that - I don't know why the heck I made it Base64Image LOL - thanks for spotting that - I've fixed it on the question... Other than that, do you think that should work? The Base64 representation of the image will be in the content/body of the POST right? – Fabricio Rodriguez Jul 24 '17 at 13:09
  • Provided they send it as the raw body and not part of some model. Yes – Nkosi Jul 24 '17 at 13:10
  • Sending Base64 does not make much sense. The ratio of output bytes to input bytes is 4:3 (33% overhead) according to Wikipedia. Indeed angular2 has got a good support for file upload. I suggest the front end developer should have a look at https://stackoverflow.com/questions/40214772/file-upload-in-angular-2 – Ralf Bönning Jul 25 '17 at 09:40
  • your front end developer can simply convert base64 image in to file – jaseelmp Jul 25 '17 at 16:29
  • Thanks rboe and jaseelmp, I will relay your messages to the front end developer... I'm not sure how to mark this question as answered, seeing as all replies were in the form of comments? – Fabricio Rodriguez Jul 26 '17 at 09:43

0 Answers0