ParsaLabs | Blog

A publication about the web and more.

File Upload With Jquery Ajax

| Comments

JQuery’s .ajax() interface is used to perform asynchronous requests to the server. In the settings parameter you can specify additional data that needs to be sent to the server with the request. But if you try and send a file, you will notice that it won’t work! Here is a trick to solve that problem.

Let’s say you have an input element (with an id of image_input) on the page. You can access the chosen file like so:

1
2
var image_input_element = find("#image_input")[0];
var chosen_file = image_input_element.files[0]

But as mentioned above, you cannot directly pass it as your ajax data. Instead, you will need to wrap it in a FormData object:

1
2
3
4
5
6
7
8
9
10
11
12
13
var fd = new FormData();    
fd.append( 'file', image_input_element.files[0] );

$.ajax({
  url: "<%= upload_url %>",
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  done: function(data){
    console.log( "ajax request done!" );
  }
});

Now, your file is properly embedded in request data. On the (Rails) server side, you can access this data with params[:file] and do what you want with it.

Comments