【问题标题】:Uploading files with Rails, Paperclip, and Backbone使用 Rails、Paperclip 和 Backbone 上传文件
【发布时间】:2025-12-19 18:35:07
【问题描述】:

我正在通过创建一个简单的图像板来学习 Rails。我希望用户能够将图像上传到服务器,然后我就可以为它们提供服务。

我正在使用 rails-backbone 和回形针。

以下是相关部分:

app/models/image.rb

class Image < ActiveRecord::Base
  attr_accessible :url
  attr_accessible :data
  has_attached_file :data, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end

app/assets/javascripts/backbone/templates/images/submit.jst.ejs

<form id="new-image" name="image" data-remote="true" enctype="multipart/form-data">
  <div class="field">
    <label for="data"> image:</label>
    <input type="file" name="data" id="data">
  </div>

  <div class="actions">
    <input type="submit" value="Create Image" />
  </div>
</form>

app/controllers/images_controller.rb

def create
  @image = Image.new(params[:image])
  respond_to do |format|
    if @image.save
      format.html { redirect_to @image, notice: 'Image was successfully created.' }
      format.json { render json: @image, status: :created, location: @image }
    else
      format.html { render action: "new" }
      format.json { render json: @image.errors, status: :unprocessable_entity }
    end
  end
end

我也运行了这个迁移:

class AddAttachmentDataToImages < ActiveRecord::Migration
  def self.up
    add_attachment :images, :data 
  end

  def self.down
    remove_attachment :images, :data
  end
end

在尝试保存名为“fruits.png”的文件时,我在控制台中得到以下输出:

Started POST "/images" for 127.0.0.1 at 2012-10-31 00:55:07 -0700
Processing by ImagesController#create as JSON
  Parameters: {"image"=>{"url"=>nil, "data"=>"C:\\fakepath\\fruits.png"}}
Completed 500 Internal Server Error in 2ms

Paperclip::AdapterRegistry::NoHandlerError (No handler found for "C:\\fakepath\\fruits.png"):
  app/controllers/images_controller.rb:16:in `new'
  app/controllers/images_controller.rb:16:in `create'

任何帮助将不胜感激!谢谢!

【问题讨论】:

  • 可能的欺骗:*.com/questions/10033425/…
  • 似乎是同样的错误,除了看起来解决方案是告诉表单表单是多部分的。我的表单有 enctype="multipart/form-data" 所以我认为这不是问题。
  • 另一个:*.com/questions/12336081/… 假设您的问题不是太本地化,请通过运行其他集成它的项目来检查您的回形针设置,例如 github.com/tors/jquery-fileupload-rails-paperclip-example
  • 我根据您提供的示例运行它,它运行良好。我不认为它是 Paperclip 本身——文件上传时永远不会正确填充 params 字段。

标签: ruby-on-rails ruby backbone.js paperclip


【解决方案1】:

Rail 的 UJS 不知道如何远程提交多部分的表单。从表单标签中删除data-remote="true"

如果表单是通过 ajax 发送的,那么除非您知道您正在使用 JavaScript 中的 FileData API,否则它可能没有被正确编码。您可以使用 XHR Level 2 和 FormData 正确编码多部分表单。在编码之前,您必须使用 FileData 读取文件内容。

【讨论】:

  • 我做了,但问题仍然存在。
  • 在检查器中打开网络面板并查看表单提交请求。从那里您可以验证它是作为多部分发送的。查看请求的标头。如果它是通过 ajax 发送的,那么除非你知道你正在使用 JavaScript 中的 FileData api,否则它可能没有被正确编码。
  • 所以看起来我将表单设置为什么并不重要。问题是 Backbone.save 使用 Backbone.sync,它使用 jQuery.Ajax,不支持文件上传。