Idan Shechter Idan Shechter - 4 months ago 20
Javascript Question

Upload base64 image to .NET webservice and convert it there

I have a function that sends data through

data:JSON.stringify(formdata)
using POST to a remove .NET webservice. I have no problem this far. What I want to do it to add also add a another value to the formdata JSON that will hold a base64 image data and send it to the server, and there I will convert it back to a JPEG image.

How can I so that? I already have a preview function that created a preview, but also create a base64 image:

function previewFile() {
var preview = document.querySelector('.uploadimage');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();

reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);

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


I see many question people asking how to upload image to the server. I want to stay with the current configuration but just pass the base64 image data to the server as a string. I see many developers struggling with that, and most of them just engine up creating a form in javascript and submitting like that.

Answer

Here is a recent way I did this:

string base64 = base64string.Substring(base64string.IndexOf(',') + 1);
byte[] imageData = Convert.FromBase64String(base64);
Image img;
using (var ms = new MemoryStream(imageData, 0, imageData.Length)) {
img = Image.FromStream(ms, true);

You will need:

using System.Drawing;

OR to simply convert to a jpg, use this:

File.WriteAllBytes("image.jpeg", Convert.FromBase64String(base64));

For sending the data I use the following JS:

function sendImage() {
    if (this.files && this.files[0]) {
        var FR = new FileReader();
        FR.onload = function (e) {
            $("#imgImage").attr("src", e.target.result); //show a preview
            //send e.target.result as a string to your webservice
        };
        FR.readAsDataURL(this.files[0]);
    }
}

I use this event to listen for uploaded files:

document.getElementById("fileid").addEventListener("change", sendImage, false);

And the front end:

<input type="file" id="fileid" />