Search code examples
ruby-on-railsrubycarrierwavegrape-api

Download image by using Grape and Carrierwave


I in my app/api/myapp/api.rb file I'm writing simple registration method:

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

As you can see, I'm using carrierwave gem to keep images of my model User. Now I'm just assigning random image from Faker gem.

How to receive image, that is sent from client and assign it to my new Model?


Solution

  • Just use the Rack::Multipart::UploadedFile as the example below.

    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