Skip to content Skip to sidebar Skip to footer

Image Upload To Web Service In Javascript

I need to upload an image to a webservice from javascript. I have to send a json string an a file(image). In java we have MultipartEntity. I have the followig code in java: HttpP

Solution 1:

For uploading images I use either Valum's ajax upload plugin or jQuery form plugin that allows to submit a normal form in an ajax way.

If you will use POST requests then don't forget to use MAX_FILE_SIZE hidden attribute:

<input type="hidden" name="MAX_FILE_SIZE" value="20000000">

Note that it must precede the file input field. It is in bytes, so this will limit the upload to 20MB. See PHP documentation for details.

Solution 2:

Assuming that your Java code is using Apache HttpComponents (what you really should have said then), your code, when augmented with

URIaWebImageUrl2=newURI("http://localhost:1337/");
FileimgPath=newFile("…/face.png");
finalStringaImgCaption="face";
// …HttpClienthttpClient=newDefaultHttpClient();
httpClient.execute(post);

submits the following example HTTP request (as tested with nc -lp 1337, see GNU Netcat):

POST / HTTP/1.1
Content-Length: 990Content-Type: multipart/form-data; boundary=oQ-4zTK_UL007ymPgBL2VYESjvFwy4cN8C-FHost: localhost:1337Connection: Keep-AliveUser-Agent: Apache-HttpClient/4.1.2 (java 1.5)

--oQ-4zTK_UL007ymPgBL2VYESjvFwy4cN8C-F
Content-Disposition: form-data; name="picture"; filename="face.png"Content-Type: application/octet-stream

�PNG[…]

The simplest solution to do something like this in HTML is, of course, to use a FORM element and no or minimal client-side scripting:

<form action="http://service.example/" method="POST"
      enctype="multipart/form-data">
  <inputtype="file" name="picture">
  <inputtype="submit">
</form>

which submits (either when submitted with the submit button or the form object's submit() method) the following example request:

POST / HTTP/1.1
Host: localhost:1337Connection: keep-aliveContent-Length: 886Cache-Control: max-age=0Origin: http://localhostUser-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryhC26St5JdG0WUaCiAccept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8Referer: http://localhost/scripts/test/XMLHTTP/file.htmlAccept-Encoding: gzip,deflate,sdchAccept-Language: de-CH,de;q=0.8,en-US;q=0.6,en;q=0.4Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

------WebKitFormBoundaryhC26St5JdG0WUaCi
Content-Disposition: form-data; name="picture"; filename="face.png"Content-Type: image/png

�PNG[…]

But since you have asked explicitly about a "javascript" solution (there really is no such programming language), I presume that you want to have more client-side control over the submit process. In that case, you can use the W3C File API and XMLHttpRequest or XMLHttpRequest2 APIs as provided by recent browsers (not the programming languages):

<scripttype="text/javascript">functionisHostMethod(obj, property)
  {
    if (!obj)
    {
      returnfalse;
    }

    var t = typeof obj[property];
    return (/\bunknown\b/i.test(t) || /\b(object|function)\b/i.test(t) && obj[property]);
  }

  varglobal = this;

  functionhandleSubmit(f)
  {
    if (isHostMethod(global, "XMLHttpRequest"))
    {
      try
      {
        var input = f.elements["myfile"];
        var file = input.files[0];
        var x = newXMLHttpRequest();
        x.open("POST", f.action, false);  // ¹try
        {
          var formData = newFormData();
          formData.append("picture", file);
          x.send(formData);
          returnfalse;
        }
        catch (eFormData)
        {
          try
          {
            var reader = newFileReader();
            reader.onload = function (evt) {
              var boundary = "o" + Math.random();
              x.setRequestHeader(
                "Content-Type", "multipart/form-data; boundary=" + boundary);
              x.send(
                  "--" + boundary + "\r\n"
                + 'Content-Disposition: form-data; name="picture"; filename="' + file.name + '"\r\n'
                + 'Content-Type: application/octet-stream\r\n\r\n'
                + evt.target.result
                + '\r\n--' + boundary + '--\r\n');
            };
            reader.readAsBinaryString(file);
            returnfalse;
          }
          catch (eFileReader)
          {
          }
        }
      }
      catch (eFileOrXHR)
      {
      }
    }

    returntrue;
  }
</script><formaction="http://service.example/"method="POST"enctype="multipart/form-data"onsubmit="return handleSubmit(this)"><inputtype="file"name="myfile"><inputtype="submit"></form>

This approach tries to use the XMLHttpRequest API. If that fails, the function returns true, so true is returned to the event handler (see the attribute value), and the form is submitted the usual way (the latter might not work with your Web service; test before use by disabling script support).

If XMLHttpRequest can be used, it is "tested"² if the file input has a files property and the object referred to by that has a 0 property (referring to the first selected File for that form control, if supported).

If yes, the XMLHttpRequest2 API is tried, which send() method can take a reference to a FormData and do all the multi-part magic by itself. If the XMLHttpRequest2 API is not supported (which should throw an exception), the File API's FileReader is tried, which can read the contents of a File as binary string (readAsBinaryString()); if that is successful (onload), the request is prepared and submitted. If one of those approaches seemingly worked, the form is not submitted (return false).

Example request submitted with this code using the FormData API:

POST / HTTP/1.1
Host: localhost:1337Connection: keep-aliveContent-Length: 887Origin: http://localhostUser-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryLIXsjWnCpVbD8FVAAccept: */*Referer: http://localhost/scripts/test/XMLHTTP/file.htmlAccept-Encoding: gzip,deflate,sdchAccept-Language: de-CH,de;q=0.8,en-US;q=0.6,en;q=0.4Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

------WebKitFormBoundaryLIXsjWnCpVbD8FVA
Content-Disposition: form-data; name="picture"; filename="face.png"Content-Type: image/png

�PNG[…]

The example request looks slightly different when the FileReader API was used instead (just as proof of concept):

POST/HTTP/1.1Host:localhost:1337Connection:keep-aliveContent-Length:1146Origin:http://localhostUser-Agent:Mozilla/5.0(X11;Linuxi686)AppleWebKit/535.1(KHTML,likeGecko)Chrome/14.0.835.202Safari/535.1Content-Type:multipart/form-data;boundary=o0.9578036249149591Accept:*/*Referer:http://localhost/scripts/test/XMLHTTP/file.htmlAccept-Encoding:gzip,deflate,sdchAccept-Language:de-CH,de;q=0.8,en-US;q=0.6,en;q=0.4Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3--o0.9578036249149591Content-Disposition:form-data;name="picture";filename="face.png"Content-Type:application/octet-streamPNG[…]

Notice that the XMLHttpRequest2, FormData and File API are having only Working Draft status and so are still in flux. Also, this approach works if the resource submitted from and the resource submitted to are using the same protocol, domain, and port number; you may have to deal with and work around the Same Origin Policy. Add feature tests and more exception handling as necessary.

Also notice that the request made using FileReader is larger with the same file and misses the leading character, as indicated in the question referred to by Frits van Campen. This may be due to a (WebKit) bug, and you may want to remove this alternative then; suffice it for me to say that the readAsBinaryString() method is deprecated already in the File API Working Draft in favor of readAsArrayBuffer() which should use Typed Arrays.

See also "Using files from web applications".

¹ Use true for asynchronous handling; this avoids UI blocking, but requires you to do processing in the event listener, and you will always have to cancel form submission (even if XHR was unsuccessful).

² If the property access is not possible, an exception will be thrown. If you prefer a real test, implement (additional) feature-testing (instead), and be aware that not everything can be safely feature-tested.

Solution 3:

you can actually invoke a service using javascript, there is a sample code for this here

if your requirement is to upload the image and make the webservice call from JS then it could be tricky.

you can simply upload the image to a server and have the server call the webservice, there are loads of tools which helps you to upload a file to a server.

Solution 4:

MultipartEntity sounds like Multipart/form-data.

You can use a regular XMLHttpRequest to make a POST request. You can use the HTML 5 FormData to build your Multipart/form-data request.

Here is an example: HTML5 File API readAsBinaryString reads files as much larger, different than files on disk

Solution 5:

I've done this before and it works, using HTML5's canvas element. I'll be using jQuery here. I'm assuming a generic image of 300px by 300px.

First, add a hidden canvas to your page :

$("body").append('<canvasid="theCanvas"style="display:none"width="300px"height="300px"></canvas>');

Then, load the image to the canvas :

var canvas = document.getElementById('theCanvas');  
var context = canvas.getContext('2d');
var imageObj = newImage();
imageObj.src = "/path/to/image.jpg";  
context.drawImage(imageObj, 0, 0, 300, 300);

Now, you can access what's on the canvas as a data string and post it to the webservice using jQuery's post function :

$.post("path/to/service", {'image':canvas.toDataURL("image/png"), 'url':'caption'},  function(file){               
    //Callback code
});  

Post a Comment for "Image Upload To Web Service In Javascript"