HTML5 FormData file upload with RubyOnRails

Caio Tarifa picture Caio Tarifa · Sep 14, 2012 · Viewed 10.9k times · Source

I using this script to upload file (one by one) with HTML5 FormData in Rails 3.2.8 application.

http://jsfiddle.net/RamPr/

$('.uploader input:file').on('change', function() {
  $this = $(this);

  $('.alert').remove();

  $.each($this[0].files, function(key, file) {
    $('.files').append('<li>' + file.name + '</li>');

    data = new FormData();
    data.append(file.name, file);

    $.ajax({
      url: $('.uploader').attr('action'),
      contentType: 'multipart/form-data',
      type: 'POST',
      dataType: 'json',
      data: data,
      processData: false
    });
  });
});

But when I upload a file, I get this error in console:

webrick/server.rb:191:in `block in start_thread' ERROR ArgumentError: invalid %-encoding ("filename.jpeg" Content-Type: image/jpeg

How can I solve this error?

Answer

Ian Selby picture Ian Selby · Sep 20, 2012

Have you seen this issue? Sending multipart/formdata with jQuery.ajax

It looks like you might be running into jQuery adding content-type headers, which causes the boundary string to be missing. From the above linked issue:

It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.

Based on that, give this a try:

$.ajax({
  url: $('.uploader').attr('action'),
  contentType: false,
  cache: false,
  processData: false,
  type: 'POST',
  dataType: 'json',
  data: data
});

I haven't tried this myself, but I suspect this might be the droids you're looking for :)