Uploading files/image with Ajax & Jquery, without submitting a form

Here is the code for uploading an image or file without submitting a form with Ajax. For this we will create object of FormData class and will append the properties of the file field in a attribute of FormData object, finally we will set the FormData object with the data key of ajax method of JQuery.

<input id="avatar" type="file" name="avatar" />
<button id="upload" value="Upload" />

We can get the parameters of file field by accessing the “file” key of the parameters hash.

Sorry to say, but the FormData class is not supported in IE. :(

If you are looking for a solution that works on all browsers have a look at Upload image without submitting form, works on all browsers.

29 comments on “Uploading files/image with Ajax & Jquery, without submitting a form

  1. Anonymous June 7, 2012 11:36 pm

    Great tutorial man….

    Saved me 2 days of gooooogling around…

    Thnk buddy,

    Keep up the good work.

  2. George September 26, 2012 2:31 pm

    Hi,
    The url in the ajax call must be a server side script that manipulates the file?or it can be a folder which the file will be saved?

    Thanks!

    • w3villa September 26, 2012 9:14 pm

      Hi George,
      The script will send you file to the server and you have to manipulate the file and store it in the folder you need.
      As I am using rails framework, we have gems like paperclip. With such gems it becomes very easy to handle the incoming file.

      Thanks.

  3. Kỳ Anh September 28, 2012 1:31 pm

    cool tutorial dude. thank you so much ;)

  4. Maneesh M.S. October 11, 2012 1:43 am

    how the formdata is using in the controller. I strucked in this
    position. can you helpme?

    • w3villa October 11, 2012 10:33 pm

      Hi Maneesh…
      Purpose of Fromdata class is to collect data from the view form and send it as parameters to the controller. You can have a look at the parameters from the browser console(extinction like firebug in mozilla).
      You need to handle parameter in your controller just like simple ajax call. Formdata does nothing in the controller.

      Thanks.

  5. w3villa October 11, 2012 10:31 pm

    Hi Maneesh,
    Purpose of Fromdata class is to collect data from the view form and send it as parameters to the controller. You can have a look at the parameters from the browser console(extinction like firebug in mozilla).
    You need to handle parameter in your controller just like simple ajax call. Formdata does nothing in the controller.

    Thanks.

  6. Babanas January 29, 2013 6:17 pm

    Nice, but useless solution without IE supporting…

  7. amol January 31, 2013 6:43 pm

    how to access this come in php

    • w3villa February 12, 2013 2:28 pm

      You need to access file parameters with method post. But as I dont use php, I am not sure how you handle form’s data.

  8. koushik February 7, 2013 12:06 pm

    This code really helpful but how to access the ajax ‘file’ data??please help…

    • w3villa February 12, 2013 2:26 pm

      Which programming language you are talking of. In rails you can get the file from params[:file]

  9. kaushank February 18, 2013 10:26 am

    hey i have created one service for uploading file and sending some parameter in json using ajax i send the whole parameter including form data to the java server api…

  10. auxiliaire March 19, 2013 6:12 pm

    thanx it’s very helpful.

  11. Anonymous April 13, 2013 11:37 pm

    it should be “data: form_data” instead of “data: file_data” on line 12.

    • w3villa April 25, 2013 10:36 am

      Thanks for the correction.

  12. David April 16, 2013 6:48 am

    doesnt work for PHP, you can’t get the file properties, only the size

  13. Gregory Guidero May 8, 2013 5:42 am

    another way the data can be retrieved is by:

    $(‘:file’).change(function(){
    var file_data = this.files[0];
    }

    is the same as var file_data = $(“#avatar”).prop(“files”)[0];

    except does not require a user to submit but merely select what img they want. I am having issues though with this code, I Don’t Know if its due to JQUERY versions or? but When I add the success and error parameters to the ajax to see why its not functioning properly it returns error 200 unexpected token and undefined. This was attempted with this base script as well as mine above with the same results. any help?

  14. faz June 4, 2013 6:11 pm

    how to get file name from returned json value?

    • w3villa June 5, 2013 6:29 pm

      faz

      From the controller code you can simply return the name of the file. Something like

      if successful
      render json: { success: true, name: @user.image.name, size: … }

      end

      and you can write ajax callback to parse the returned json result.

  15. Rajesh July 23, 2013 6:43 pm

    Hi, No code error. But, the file is not uploaded into the folder.

    Can you please provide some suggestion?

    $(“#upload”).live(“click”, function() {
    var file_data = $(“#avatar”).prop(“files”)[0]; // Getting the properties of file from file field
    var form_data = new FormData(); // Creating object of FormData class
    form_data.append(“file”, file_data) // Appending parameter named file with properties of file_field to form_data
    form_data.append(“user_id”, 123) // Adding extra parameters to form_data
    console.log (file_data);
    console.log (form_data);
    $.ajax({
    url: “/upload_avatar”,
    dataType: ‘script’,
    cache: false,
    contentType: false,
    processData: false,
    data: form_data, // Setting the data attribute of ajax with file_data
    type: ‘post’
    })
    })

    Thanks

    Regards

    A Rajesh khanna

  16. Tushar August 1, 2013 12:53 pm

    realley useful code for FormDATA

  17. Mohan August 1, 2013 6:11 pm

    How can we call success function after all done?

    • w3villa August 19, 2013 12:14 pm

      Just use the success callback of $.ajax

      $.ajax({
      url: “/upload_avatar”,
      dataType: ‘script’,
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: ‘post’,
      success: function() {
      doSomeThing();
      }
      })

      • aamir July 11, 2014 6:53 am

        url: “/upload_avatar”, what is ?

  18. massimo_indie September 12, 2013 12:33 pm

    Bad solution, because it doesn’t work in IE < 10

    • jerome September 27, 2013 12:24 pm

      also, very bad browser who never follow the international convention but sale his shit (it s a shame).
      the great solution his to definitively ignore ie and ever said that you need chrome or firefox (it’s better more and free).

  19. Ta Duc July 15, 2014 11:52 am

    You are saving my life bro :D

Leave a Reply