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?
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
contentTypeoption tofalse, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave theprocessDataflag set tofalse, 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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With