Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 FormData file upload with RubyOnRails

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?

like image 692
Caio Tarifa Avatar asked Sep 14 '12 20:09

Caio Tarifa


1 Answers

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

like image 109
Ian Selby Avatar answered Nov 07 '22 12:11

Ian Selby