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:

  1.  
  2. $.ajaxFileUpload(
  3. {
  4. url:serverurl,
  5. secureuri:false,
  6. fileElementId:elementId,
  7. dataType: 'json',
  8. success: function (data, status)
  9. {
  10. /* show success message */
  11. },
  12. error: function (data, status, e)
  13. {
  14. /* handle error */
  15. }
  16. });
  17.  

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

See demo

Internals:

Generate a form at runtime and post the file using

  1.  
  2. form.enctype = 'multipart/form-data';
  3.  

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!! :-)

48 thoughts on “Ajax File upload – Jquery Plugin

  1. 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&param2=value2

    I will study about posting parameters using form while uploading file and will get back to you .

  2. 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.

  3. 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?

  4. 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.

  5. 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!

  6. 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??

  7. 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?

  8. 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..?

  9. 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.

  10. 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.

  11. 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

  12. 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.

  13. 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)
    {
    }
    });

  14. 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

  15. Thanks Kirzilla, I hope this solves problem of many of us who wanted to send parameters while uploading the file.

  16. 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

  17. 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.

  18. 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”) ;

  19. 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.

  20. 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!

  21. 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

  22. 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

  23. 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 .

  24. @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

  25. hey, hey, hey…!!

    How could we pass the other textfields along with the
    File Upload within a single FORM with a submit button
    enhanced by this Ajax (JQuery) Request?

    Is there any example for the JSP developer?

  26. help me with the action method in servlet…Code snippet would be much more helpful.Thanks

  27. hello, I am trying to use this plugin with spring MVC 3.0 to receive JSON response but it is not working with Firefox. It start download manager to download JSON. I have also tried to set content type as “text/html” but as I am using responsebody annotation, it is getting override when JAXON api try to create JSON object from my response bean… can any put some light on this to resolve this issue …

  28. Hi i also have the same problem in Firefox 3.5 . the json response is download by the download manager . but it is working fine in the internet explorer. more over i didnt change the code too much. please help me if any one find out the solution

  29. Hi Aditya ,

    I got an issue with IE while uploading files using this library.on chrome/FF it works fine. but Oon IE im hitting the success call back with ‘false’. when I check the network log there was no request has been made.

    $.ajaxFileUpload ({
    url:that.actionUrl + “&a=ideaFileUpload&ideaId=” + localIdeaId + “&ideaMediaContentName=ideaMediaContent” + that.uploadContentCount,
    secureuri:false,
    fileElementId:’ideaMediaContent’+that.uploadContentCount,
    dataType: ‘json’,
    success: function (data2) {
    that.uploadContent(successCalling ,localIdeaId,AddIdeaData);
    },
    error: function (data2) {
    if(that.uploadCompleted){
    successCalling(AddIdeaData);
    }else{
    that.__deleteIdea(localIdeaId, false);
    $(‘#addIdeaForm’).show();
    that.showUserMessage(that.getMessage(‘uploadIdeaMediaContentError’));
    }
    }
    });

    any suggestion will be really appriciate

  30. hello, I am trying to use this plugin with spring MVC 3.0 to receive JSON response but it is not working with Firefox. It start download manager to download JSON. I have also tried to set content type as “text/html” but as I am using responsebody annotation, it is getting override when JAXON api try to create JSON object from my response bean… can any one put some light on this to resolve this issue … Thaks for all help..

  31. Hi,

    I used this plugin and it’s great, working fine on IE, FF and chrome. But Im having problems in opera, every time I try to upload I got this error, “SyntaxError: at index 5 in “data = “: expected expression, got “. So I went down and tried looking into ajaxfileupload.js file, added some alerts here and there and viola! it worked! But when I removed the alerts it didn’t work again. Anybody encountered the same problem as me? Any solution to this? Hope you can help me.

  32. Hi, I am having issues with this plugin in Chrome. It works great in FF and IE, but not in Chrome. Any advise?

    Thanks

    Sharma

Leave a Reply