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.

  • Anonymous

    Great tutorial man….

    Saved me 2 days of gooooogling around…

    Thnk buddy,

    Keep up the good work.

  • George

    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

      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.

  • http://www.facebook.com/long.ky.anh Kỳ Anh

    cool tutorial dude. thank you so much ;)

  • Maneesh M.S.

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

    • w3villa

      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.

  • w3villa

    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.

  • Babanas

    Nice, but useless solution without IE supporting…

  • amol

    how to access this come in php

    • w3villa

      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.

  • koushik

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

    • w3villa

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

  • kaushank

    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…

  • auxiliaire

    thanx it’s very helpful.

  • Anonymous

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

    • w3villa

      Thanks for the correction.

  • David

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

  • Gregory Guidero

    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?

  • Pingback: Upload image without submitting form, works on all browsers. | w3villa Official Blog

  • faz

    how to get file name from returned json value?

    • w3villa

      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.

  • Rajesh

    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

  • Tushar

    realley useful code for FormDATA

  • Mohan

    How can we call success function after all done?

    • w3villa

      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

        url: “/upload_avatar”, what is ?

  • http://indie-game.blog.tut.by/ massimo_indie

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

    • jerome

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

  • Ta Duc

    You are saving my life bro :D

  • https://www.facebook.com/gabousk8 Gabouh Lopez

    @amol, @koushik better late than never, to access in the PHP file, put the form_data in the data: field of the ajax call and in the php file access to values with $_POST[‘user_id’]