ruby-on-rails – 使用RubyOnRails上传HTML5 FormData文件

我使用这个脚本在Rails 3.2.8应用程序中使用 HTML5 FormData上传文件(逐个).

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
    });
  });
});

但是当我上传文件时,我在控制台中收到此错误:

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

我该如何解决这个错误?

解决方法

你见过这个问题吗? Sending multipart/formdata with jQuery.ajax

看起来您可能会遇到添加内容类型标头的jQuery,这会导致边界字符串丢失.从以上链接的问题:

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,jQuery will try to convert your FormData into a string,which will fail.

基于此,尝试一下:

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

我自己没试过,但我怀疑这可能是你正在寻找的机器人:)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...