Questieme
Questieme

Reputation: 993

How to make a POST method for an image?

So I've been working on this API and I didn't have issues until now when I tried figuring out how to make a POST method that takes an image as a parameter. In theory, this is how it should work:

From a web page, you will upload an image and then using the route to the API, the image information will be sent to the database like this: enter image description here

Now, I've been searching for an answer to this on different several pages but none of them actually helped. In fact, the only guides that I've found were about integrating that method into a Web Api (see https://www.c-sharpcorner.com/article/uploading-image-to-server-using-web-api-2-0/) but this doesn't really work for me as I can't inherit some of the methods in my solution. For example, using the link above, I had issues with HttpContext.Current, and I would guess that is because of the solution that I am currently using. However, that's another question to be asked.

So my methods look pretty much like this:

public class RecipeController : Controller
{
    private readonly Func<SqlConnection> _connFactory;
    public RecipeController(Func<SqlConnection> connFactory)
    {
        _connFactory = connFactory;
    }

    [Route("v1/recipe/{recipeBy}")]
    [HttpGet()]
    public List<Recipe> GetRecipes(string recipeBy)
    {
        using (var con = _connFactory())
        {
            con.Open();
            return con.Query<Recipe>("SELECT * FROM dbo.Recipe WHERE RecipeBy = @recipeBy", new { recipeBy }).ToList();
        }
    }
    ....

I am using Dapper to pass the values to the database.

Therefore, my question is: How can I write a POST method that takes an uploaded image as a parameter and then passes it to the database? I do realize that this question is pretty vague, as I didn't even provide reproducible code. The thing is, until now I didn't even figure out a correct way to start working on, so I couldn't really provide any useful code that you can help me with. Any tips, hints, advice, tutorials... Anything is welcome!

Upvotes: 0

Views: 426

Answers (1)

Gary
Gary

Reputation: 732

You can accomplish this by using the Html5 FileReader class to read the image to a string on the client-side and then post this to the api end-point:

function UploadImage()
{
    var file = input[0].files[0];

    var reader = new FileReader();

    reader.onloadend = function () {
        var imageDataString = reader.result;
        // post the fileString value to your api here
    }

    if (file) {
        reader.readAsDataURL(file);
    }
}

Then on your Controller you would convert the Base64String into a byte[] and store it in your db:

if (imageDataString != null && imageDataString != String.Empty)
{
    string imageDataParsed = imageDataString.Substring(imageDataString.IndexOf(',') + 1);
    byte[] imageBytes = Convert.FromBase64String(imageDataParsed);
}

Upvotes: 2

Related Questions