[英]Uploading files with Rails, Paperclip, and Backbone
我正在通過創建一個簡單的圖像板來學習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
應用程序/資產/ Java腳本/骨干網/模板/圖像/ 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'
任何幫助,將不勝感激! 謝謝!
Rail的UJS不知道如何遠程提交多部分表單。 從表單標簽中刪除data-remote="true"
。
如果表單是通過ajax發送的,則除非您知道您正在使用JavaScript中的FileData API,否則可能無法正確編碼。 您可以使用XHR Level 2和FormData正確編碼多部分表單。 必須先使用FileData讀取文件內容,然后才能對其進行編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.