Shyamal Parikh
Shyamal Parikh

Reputation: 3068

How to post and get data uri image from web api?

I am trying to post data uri image from javascript to backend asp.net webapi. However, it gives me input is not a valid Base-64 string error. Now, I understand that it may be due to "data:image/png;base64," part that the data uri contain.

Now, even if I remove this part from the data uri and send only the rest of the string to server, how do I store the Base-64 string on the server?

Moreover, how to retrieve this data as image from webapi?

NOTE: Image would be less than 200kB size and hence is to be stored as varbinary(Max) in sql server.

Upvotes: 1

Views: 2011

Answers (2)

Nagendra Hari Karthick
Nagendra Hari Karthick

Reputation: 483

The thing is you should convert your image to byte[] and store it in your server as varbinary

 byte []arr = new byte[image1.ContentLength];
 image1.InputStream.Read(arr, 0, image1.ContentLength);

While retrieving you should convert the varbinary data to base64 string and base 64 string to image

string imageBase64Data = Convert.ToBase64String(img); 

Here comes the important part the above code convert varbinary to base64string.It should be in proper format to display the image.Thats what the following code does

  string imageDataURL = string.Format("data:image/png;base64,{0}", asd);
  Session["Photo"] = imageDataURL;

Now you can able to view your image

Upvotes: 2

user5936409
user5936409

Reputation:

Post the image from your client in a for of string, w/o specifying the type. On your action you can get the image in the following way :

    var bytes = Convert.FromBase64String(yourStringHere);
    using (var ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);
    }

Upvotes: 0

Related Questions