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:
HttpPost post = new HttpPost( aWebImageUrl2 );
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
entity.addPart( "picture", new FileBody((( File ) imgPath )));
// For usual String parameters
entity.addPart( "url", new StringBody( aImgCaption, "text/plain", Charset.forName( "UTF-8" )));
post.setEntity( entity );
Now I need to do the same image upload in javascript.
But in javaScript I didn't find any equivalent of MultipartEntity. Please Suggest any solutions.
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.
MultipartEntity sounds like
Multipart/form-data
.You can use a regular
XMLHttpRequest
to make a POST request. You can use the HTML 5FormData
to build yourMultipart/form-data
request.Here is an example: HTML5 File API readAsBinaryString reads files as much larger, different than files on disk
Assuming that your Java code is using Apache HttpComponents (what you really should have said then), your code, when augmented with
submits the following example HTTP request (as tested with
nc -lp 1337
, see GNU Netcat):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:which submits (either when submitted with the submit button or the form object's
submit()
method) the following example request: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):
This approach tries to use the XMLHttpRequest API. If that fails, the function returns
true
, sotrue
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 a0
property (referring to the first selectedFile
for that form control, if supported).If yes, the XMLHttpRequest2 API is tried, which
send()
method can take a reference to aFormData
and do all the multi-part magic by itself. If the XMLHttpRequest2 API is not supported (which should throw an exception), the File API'sFileReader
is tried, which can read the contents of aFile
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:
The example request looks slightly different when the FileReader API was used instead (just as proof of concept):
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 thereadAsBinaryString()
method is deprecated already in the File API Working Draft in favor ofreadAsArrayBuffer()
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.
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.
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 :
Then, load the image to the canvas :
Now, you can access what's on the canvas as a data string and post it to the webservice using jQuery's post function :