Ajax File upload – Jquery Plugin
Ajax file upload is very essential requirement for Ajax enabled web applications. If you are using Jquery as javascript library for developing your web-app, you can use this Ajax file upload plugin:
How to use:
$.ajaxFileUpload( { url:serverurl, secureuri:false, fileElementId:elementId, dataType: 'json', success: function (data, status) { /* show success message */ }, error: function (data, status, e) { /* handle error */ } });
Very similar to Jquery Ajax syntax, isn’t it? pass the server URL i.e. servlet URL and elementId i.e. value of id attribute of “file” input.
Where to get it? download from here
Internals:
Generate a form at runtime and post the file using
form.enctype = 'multipart/form-data';
Generally form submit is attached with the document object and form submit refreshes the main document. This plugin also generates an iframe and form submit event is attached to that iframe, so main page doesn’t get refreshed at the time of form submit.
Happy uploading!!
Most Commented Posts
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.
Comments
I am not sure about the form but you can easily pass few more parameters in query string of URL on which you are uploading the file e.g. in above post
serverurl can be /server/upload?param1=value1¶m2=value2
I will study about posting parameters using form while uploading file and will get back to you .
Aditya, you can use my ajax upload plugin if you want to send additional parameters or use custom file upload button.
I posted this on the jquery forum as well. I’m using a java servlet which is sending back a content-type “application/json” and the json string { “result” : “success”}.
Using your plugin, the file uploading itself works fine, but the response from the servlet is not getting handled by the plugin. Instead I see an attachment popup in my browser with the servlet url I passed into the plugin instead of the callbacks getting called.
Please let me know if you have any idea why this might be happening. Otherwise, great plugin, I only modified it to add in a hidden parameter to the form, aside from that it works great. Thank you.
to update regarding my error. Now I’m getting to the error callback. And I’m getting a:
TypeError io.contentDocument.document is undefined happening here in the code:
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
however looking at the html via Firebug, i can see the data did come back from the servlet:
{“result”:”success”}
</iframe
Any idea what’s going on here?
Matt, on a quick look i can say that you just need to set your response type at servlet to “text/html” and not to “application/json”.
That’s what i did while using it and it worked. I guess it takes json as text.
Do let me know if does not work, I will try to test it my self.
Aditya, that seemed to do the trick thanks! I guess I just assumed that since your code specified json or xml as the datatypes that it would actually need that specified in the ContentType. Either way, I really appreciate your quick response, this seems to work great for me now. cheers!
[...] If you are using Spring framework for your project/product you can do this using latest version of commons-fileupload which lets you write your own ProgressListener using which you can limit file upload size and monitor the upload process as well. We are using Ajax in our project and for file upload we are using ajaxfileupload (see more in detail) [...]
I am trying to use this plug-in to allow users to upload a comment accompanied by an image to our site. I have it working, but no matter what I do, I can’t get the function to accept the json return (which is the HTML for that new comment) without getting an error or having the function “un-set” the return json (to undefined).
Bottom line, I have tested this for hours and it appears there is a bug… as soon as the “success:” function encounters a “<” followed by any other character, it renders the return data to be undefined. I am using PHP’s json_encode() as well as tried to encode it manually. I have tried to add a second level of encoding to hide the “<d” from it… urlencode sort of works, but if you decode it, again, it fails in that function.
Not sure what is going on, I have been successfully passing HTML back successfully in this manner in other jQuery functions like $.post.
Any thoughts??
Nice plugin. However, I have 2 comments:
1) there’s no official way to get simple “r.responseText” as “data” in uploadHttpData function. Of course, you can set type to some non existing “text” or whatever, but this option should be inserted into code or at least documented.
2) Clone with parameter “true” to also clone the event handlers: “var newElement = $(oldElement).clone(true);”
Are you planning any new releases?
nice plugin. i can upload my file without refresh my main page. thanks..
however, can send data beside file, like input type other?can you help me please..?
I’m using this plugin with Spring MVC framework. I’m facing problem with returning JSON object. From server i’m returning a JSON object which is not recognized by the plugin OnComplete callback. I tried setting response to content-type to application/javascript and text/html. I’m using browser FF 3.5. Can some one help me out with this issue.
Hi Arun, I am also using Spring MVC with ajaxfileupload in one of my projects and it works fine with
response.setContentType(“text/html”);
This should solve your problem.
Hi, How can i pass parameters in this method. i want to pass n number of parameters to the method call I don’t want to next to the URL.
$.ajaxFileUpload(
{
url:serverurl,
secureuri:false,
fileElementId:elementId,
dataType: ‘json’,
success: function (data, status)
{
/* show success message */
},
error: function (data, status, e)
{
/* handle error */
}
});
Thanks
Hi Ravi,
Thanks for your comment and time.
if you do not to use serverurl for passing additional parameters than the only solution is to modify the plug-in’s source code. As of now it is just posting the file using the elementid , if you want to post more parameters you can change the source code and do that else you can use serverurl for sending your parameters to server.
It is really easy to send additional vars, but you should slightly modify ajaxfileupload.js file.
1. Find this string $(form).attr(‘target’, frameId);
2. After this string add following
jQuery.each(s.ppost, function(i, val) {$(form).append(”);});
3. Now you can easily add any POST variables as you wish.
$.ajaxFileUpload(
{
url:serverurl,
secureuri:false,
fileElementId:elementId,
ppost : {
‘var1′ : ‘value1′,
‘var2′ : ‘value2′
},
dataType: ‘json’,
success: function (data, status)
{
},
error: function (data, status, e)
{
}
});
WordPress has blocked HTML in step #2
jQuery.each(s.ppost, function(i, val) {$(form).append(‘###input type=”hidden” name=”‘+i+’” value=”‘+val+’” /___’);});
replace ### with opening tag
replace ___ with closing tag
Thanks Kirzilla, I hope this solves problem of many of us who wanted to send parameters while uploading the file.
[...] have already written about the Ajax file upload on this blog and found this another plug-in of Jquery for Ajax file upload. Looks like an evolved plug-in with [...]
Can i use this plug in with java, actually i was earlier using the submit in jsp to submit the complete form. form was of enctype = multipart. Now since we are only passing the elementId then how to access the file content on the server side. does any body has code for the servlet also to be used with this ajax call on server side
I have been using this plugin to upload files for sometime. I have been getting an error with large image files. It is making the post but there are no files attached in the request. It seems to be some type of timing issue. If I add breakpoints to my javascript in firebug it uploads them correctly. Is anyone else having this problem or has someone found a solution to it.
Thank you very much for this extraordinary plugin. This is the only one out there that works without headaches.
I recommand to move the temporary file and to rename it.
1. open doajaxfileupload.php
2. search and comment out @unlink
3. add the folowing
move_uploaded_file($_FILES['fileToUpload']['tmp_name'], “pathname/yourfile.ending”) ;
Today I observed a very strange cache problem with google chrome. No additional variabels could be send – without any visible reason. After deleting the browser cache I was everything ok again. Please keep it in mind if something simmilar happens to you. Personaly I thing it’s a browser bug.
@Kirzilla Thank you so much about the additional code. You saved my day.
A small addition. I wanted to allow only the file of type JPG. If you d’like it to, then follow the steps:
1. Open doajaxupload.php
2. Find the elseif line
3. Add after the closing brackets:
elseif(!$_FILES['fileToUpload']['type']==”image/jpeg”)
{
$error = ‘Image file hast to be a JPG!’;
}
4. Voila!
Is there any way to use this control via .ashx handler file in asp.net.
what I am trying to do is upload a file.
It goes to the handler file uploades it to the folder and later on it gives me an error as
“Syntax error”.
can u ust tell me where am I wrong
Hey Krishna,
I am not having in-depth knowledge of .net and MS technologies and so I did a search for your query and found this
http://www.eggheadcafe.com/software/aspnet/33475918/ajax-and-ashx-handlers.aspx
The writer tried to explain the problem with ajax requests which you are using ashx,, see if you find any help in there.
wzup
I get a weird error when i try to move the file to my server files.
If i try
move_uploaded_file(tmp_name, locationFile)
with the correct values I only get error if i change the location
Missing } in XML
if i just put the name of the uploaded file instead of the location everything works fine but the image is no where to be found
anybody got any idea’s ?
Thnx Robin
Is there any way to assign a dynamic value for “fileElementId”? Our requirement mandates this. But I found the name of the variable given for the “fileElementId” should match variable given for the input parameter at Controller Action method in ASP.Net MVC 1.0 .
@Kirzilla
hey i m sending data with form as per u said, it solves my problem but thing is when i return response from server side it shows me exception ‘not enough argument problem in frame etc’, why this happening also, wat to do if i want to send this as- async-false, and get response in responseText.? pls help

is there a way to upload other fields with the file? or even a form? (maybe the upload form?)