使用Grape和Carrierwave下载图像

时间:2015-07-25 09:24:45

标签: ruby-on-rails ruby carrierwave grape-api

我在我的NONE文件中我正在编写简单的注册方法:

app/api/myapp/api.rb

如您所见,我使用carrierwave gem来保留模型params do requires :email, type: String, regexp: /.+@.+/, allow_blank: false requires :password, type: String, allow_blank: false requires :name, type: String, allow_blank: false requires :surname, type: String, allow_blank: false requires :person, type: Integer, allow_blank: false end post :register do User.create!(email: params[:email], password: params[:password], name: params[:name], surname: params[:surname], remote_avatar_url: Faker::Avatar.image) end 的图像。现在我只是从Faker gem中分配随机图像。

如何接收从客户端发送的图像并将其分配给我的新模型?

1 个答案:

答案 0 :(得分:0)

只需使用Rack::Multipart::UploadedFile作为示例。

desc 'Upload Image.'
params do
    requires :file, :type => Rack::Multipart::UploadedFile
    requires :id, :type => Integer
end
post ':id/avatar' do
    File.open(params[:file].tempfile, 'r') do |f|
        # Do whatever you need with this file. 
        # Here, you can store it in the server filesystem or in your database.
    end
end