HTML5 FormData file upload with RubyOnRails

笑着哭i 提交于 2019-12-05 22:25:40

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/12431760/html5-formdata-file-upload-with-rubyonrails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!