2012-06-28 28 views
0

我想通過PUT請求在服務器上使用REST API上傳附件。我可以通過將二進制文件放在請求體中來做到這一點,但我也想將此文件保存爲使用回形針保存附件的模型的附件。Ruby on Rails:REST API +文件上傳+回形針

這是我目前參與的類定義:

class Cl < ActiveRecord::Base 
    after_update :save_tses 
    validates_associated :tses 

    has_many :tses 

    ...truncated... 

    def save_tses 
    tses.each do |ts| 
     ts.save(false) 
    end 
    end 

end 

class Ts < ActiveRecord::Base 
    has_attached_file :tsa, :styles => { :thumb => {:geometry => "100x141>", :format => :jpg} }, 
    :path => ":rails_root/public/system/:attachment/:id/:style/:friendly_filename", 
    :url => "/system/:attachment/:id/:style/:friendly_filename" 

    belongs_to :cl 

    def friendly_filename 
    "#{self.tsa_file_name.gsub(/[^a-zA-Z0-9_\.]/, '_')}" 
    end 
end 

我就好使用HTML頁面的文件上傳保存附件。我想在一個控制器上通過PUT請求接收文件作爲二進制數據。

有什麼建議嗎?

回答

0

明白了,

# controller.rb 

def add_ts 
    # params[:id] 
    # params[:tsa] 

    @cl = Cl.find(params[:id]) 
    ts = @cl.tses.build(:name => "#{@cl.name}_#{Time.now.to_i}") 

    ts.tsa = params[:tsa] 
    if ts.save 
    render :json => {:status => "OK"} 
    else 
    render :json => {:status => "ERROR"} 
    end 
end 

# Test 

curl -F "[email protected]" "http://host/cl/474/add_ts" 
=> {"status":"OK"}