0

How can I get an image from DOM and then upload it via ajax?

my_img_ele = document.getElementById("my_img");

This is the ajax call

    var xmlHttp=new XMLHttpRequest();
    xmlHttp.open("POST", "site", true);
    var formData = new FormData();  
    formData.append(IMG_HERE); 
    xmlHttp.send(formData);

What I have been doing is just sending the url and then looking up the image server side. But I figure this will be quicker.

EDIT: Note that the user is not uploading an image via a form. It's an img element.

user984003
  • 28,050
  • 64
  • 189
  • 285
  • take a look at this: http://www.sitepoint.com/html5-ajax-file-upload/ – karaxuna Jun 21 '13 at 14:28
  • That deals with forms. Not sure how to send the image starting with an img element. – user984003 Jun 21 '13 at 14:31
  • You can use a canvas element to draw the image, then get the data using canvas: http://stackoverflow.com/questions/934012/get-image-data-in-javascript – 000 Jun 21 '13 at 14:34
  • 1
    Aren't there cross-domain issues here? Not sure if you can "steal" images from other domains. – gen_Eric Jun 21 '13 at 14:35
  • I can get everything else so why not the image? It's already "there" in the browser. – user984003 Jun 21 '13 at 14:43
  • @Joe Frambach, canvas may be the way to go. – user984003 Jun 21 '13 at 14:45
  • 1
    @user984003: If the `` is on a different domain, you can't use canvas to get it as base64. You will get a security error when you try to read the canvas' data. http://jsfiddle.net/pHER5/ – gen_Eric Jun 21 '13 at 15:03
  • 2
    How about instead of uploading the image data, why not just send the image's URL and have the server download it? I can't sending the image via AJAX quicker than sending the URL. – gen_Eric Jun 21 '13 at 15:05
  • "user is not uploading an image via a form. It's an img element", - still not clear what you want to do !! – Premshankar Tiwari Jun 24 '13 at 06:07
  • @user984003, I understand that you are not submitting the form. But you are still uploading the image via AJAX. My updated answer addresses that. – Om Shankar Jun 24 '13 at 06:10

2 Answers2

4

If you were asking "upload images via AJAX", using the FormData the answer can be simpler and easily searchable on the internet.

Kindly see if this link addresses your question.

To get an image from the DOM, you would use the same above. But instead of submitting the form, you would be reading the DOM img element as a dataURI.

Check the FIDDLE for the following code's HTML:

var originalImage = document.getElementById("image"),
    canvas = document.getElementById('canvas'),
    context = canvas.getContext('2d'),
    formdata = false,
    dummy = document.getElementById('dummy'),
    newImage = new Image();

if (window.FormData) {  
    formdata = new FormData();  
}  

newImage.onload = function(){
    // width and height here should be the same as original image
    // detect before-hand, using jQuery(el).width() /.height() on the DOM element
    context.drawImage(newImage, 0, 0, 400, 300);
}

newImage.src = originalImage.src;

  // traditional ajax and jQuery, no HTML5
if (formdata) {
    var canvasToDURI = canvas.toDataURL();
    formdata.append("image-data", canvasToDURI);

    // yay!, jQuery
    $.ajax({  
      url: "upload.php",  
      type: "POST",
      data: formdata,
      processData: false,  
      contentType: false,  
      success: function (res) {  
        // do some thing !
        dummy.innerText = 'Image data sent !';
      },
      error: function(a, b, c) {
        dummy.innerText = 'The following data was not sent due to : ' + b + ' -- '+ c + ' \n\n' + canvasToDURI;
      } 
    });  
}

If FormData is also not supported, you can create a form element and change the enctype of the form to "multipart/form-data" and send the data using JavaScript in an AJAX call, without submitting the form.

Om Shankar
  • 7,989
  • 4
  • 34
  • 54
  • 3
    Care to explain the down-vote (and hence, keep up the SO spirit?) – Om Shankar Jun 24 '13 at 05:51
  • When I try this in my console I get `Uncaught DOMException: The operation is insecure.` Maybe browser security restrictions have changed since this was posted in 2013. – chmac Nov 19 '21 at 16:48
1

Your figure is obviously wrong. Here's the thing, an image element is nothing else than a DOM node, containing the URL of the image, the image itself get downloaded by the browser, so on a client machine it's only available in the browser memory. And even is somehow you gain acces to the browser memory (cache), consider that based on the clients connection it is highly probable that uploading it from there is way slower than dowloading it server side from the original source. The other solution is that you download the image based on the URL (img.src) via ajax get simply detour it with an other ajax in the first ones callback, but it's of course means that the image travels averagely two times more.

  • +1, Exactly. What's the point in reading the DOM element and extracting the image, when you have the URL of the image readily available! – Om Shankar Jun 24 '13 at 06:13
  • @OmShankar There's definitely a point. Captcha image usually gets changed on each request. So if someone is trying to get the current visible image, he can not just use the url. – Shazzad Nov 28 '16 at 14:35