1

I'm trying to post the content of an image element to my controller so I can store it in my database with the use of an element.

The image src format is something like this:

data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAMUAAAEACAYAAAADarJDAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEwAACxMBAJqcGAAAFCxJREFUeJzt3XuUnHV9x/HP9zuzu0kAEUKicqyGGsAbF41ELAm7syG7swmCye5ka22otF6rYqmKp3houng5R9GDtl4OwvFCC6e72QkihMwmZGc3IWop0SqXQ2qUtV6qyQZSkkAu83y//SM7usRNMjPP73l+z8x+X39yTr7PN+R57zO3fQYwxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMYlGvheYLhbctqDp1DNeMhspOosomE2qpxNRSxCghYFmENJQlJRxiAmHVfUQNLUXGuyh5u

Here is my javascript:

$("#submit").click(function () {
    var data = new FormData();
    data.append("image", $('#myImage').attr.src);
    $.ajax({
        url: "/default/upload/",
        type: "POST",
        processData: false,
        contentType: false,
        data: data,
        success: function (response) {
            //code after success
            alert("succes");
        },
        error: function (er) {
            alert(er);
        }
 });

and here is my controller method:

[HttpPost]
public void Upload(string image)
{
    Console.WriteLine("Do Something");
}

My breakpoint is triggered but my image string just contains undefined

Tân
  • 1
  • 15
  • 56
  • 102
Fross
  • 122
  • 13
  • Its not clear what you are asking. Why would you send an image back to the controller that the controller sent to the client? –  Nov 15 '18 at 10:31
  • I'm only sending the image to the controller, not sending it back to the client. I'll try to update my question to clarify – Fross Nov 15 '18 at 10:34
  • But where did the image come from? –  Nov 15 '18 at 10:35
  • From the clipboard. I'm using javascript to paste any image in the users clipboard to an tag on the site. When they press submit on my form, I then need to save the image they pasted as well – Fross Nov 15 '18 at 10:39

2 Answers2

1

I think the problem comes from this line:

data.append("image", $('#myImage').attr.src);

And the solution is:

data.append("image", $('#myImage').attr('src'));

or if you're using jquery version 1.6 or later:

data.append("image", $('#myImage').prop('src'));

My breakpoint is triggered but my image string just contains undefined

That's because $('#myImage').attr.src returned undefined. Then, you sent the value to server. And of course, image caught undefined value.

新Acesyyy
  • 1,152
  • 1
  • 3
  • 22
Tân
  • 1
  • 15
  • 56
  • 102
0

First you can post image src to controller as original string by removing data:image/gif;base64; from src string

Then you convert this base64 string to binary and save into database

byte[] imageBinary = Convert.FromBase64String(srcBase64String);
Khai Nguyen
  • 935
  • 5
  • 17