简体   繁体   中英

Uploading files with Rails, Paperclip, and Backbone

I'm learning Rails by creating a simple imageboard. I want users to be able to upload images to the server and then I will be able to serve them.

I'm using rails-backbone and paperclip.

Here are the related portions:

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

I also ran this migration:

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

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

Upon attempting to save a file named "fruits.png", I get this output in the console:

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'

Any help would be appreciated! Thanks!

Rail's UJS doesn't know how to remote submit a form that is multipart. Remove data-remote="true" from the form tag.

If the form is being sent via ajax then chances are it's not being encoded correctly unless you know you are using the FileData API from JavaScript. You can encode multipart forms correctly using XHR Level 2 and FormData . Before you can encode it you must read the file contents in using FileData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM