2

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

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

以下是相关部分:

应用程序/模型/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>

应用程序/控制器/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'

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

4

1 回答 1

1

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

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

于 2012-10-31T15:45:01.720 回答