使用 Grape 和 Carrierwave 下载图像
Download image by using Grape and Carrierwave
我在我的app/api/myapp/api.rb
文件中写了简单的注册方法:
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
如您所见,我正在使用载波 gem 来保存我的模型 User
的图像。现在我只是分配来自 Faker gem.
的随机图像
如何接收从客户端发送的图像并将其分配给我的新模型?
就用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
我在我的app/api/myapp/api.rb
文件中写了简单的注册方法:
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
如您所见,我正在使用载波 gem 来保存我的模型 User
的图像。现在我只是分配来自 Faker gem.
如何接收从客户端发送的图像并将其分配给我的新模型?
就用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