Download file using grapes and paper clips

I am working on a REST API, trying to load a user image using

  • grape micro frame
  • paperclip gem but it does not work showing this error.
  • rails version - 3.2.8

No handler found for #<Hashie::Mash filename="user.png" head="Content-Disposition: form-data; name=\"picture\"; filename=\"user.png\"\r\nContent-Type: image/png\r\n" name="picture" tempfile=#<File:/var/folders/7g/b_rgx2c909vf8dpk2v00r7r80000gn/T/RackMultipart20121228-52105-43ered> type="image/png">

I tried checking the clip with the controller and it worked, but when I try to download via grape api it does not work, my message header is multipart / form-data p>

My download code is

  user = User.find(20) user.picture = params[:picture] user.save! 

So if it is not possible to upload files via grapes, is there an alternative way to upload files via REST api?

+6
source share
3 answers

@ ahmad-sherif solution works, but you lose the original_file (and extension), and this can provide examples with preprocessors and validators. You can use ActionDispatch::Http::UploadedFile as follows:

  desc "Update image" params do requires :id, :type => String, :desc => "ID." requires :image, :type => Rack::Multipart::UploadedFile, :desc => "Image file." end post :image do new_file = ActionDispatch::Http::UploadedFile.new(params[:image]) object = SomeObject.find(params[:id]) object.image = new_file object.save end 
+14
source

Perhaps a more consistent way to do this is to define a paperclip adapter for Hashie :: Mash

 module Paperclip class HashieMashUploadedFileAdapter < AbstractAdapter def initialize(target) @tempfile, @content_type, @size = target.tempfile, target.type, target.tempfile.size self.original_filename = target.filename end end end Paperclip.io_adapters.register Paperclip::HashieMashUploadedFileAdapter do |target| target.is_a? Hashie::Mash end 

and use it "transparently"

  user = User.find(20) user.picture = params[:picture] user.save! 

added to wiki - https://github.com/intridea/grape/wiki/Uploaded-file-and-paperclip

+8
source

You can pass the File object that you received in params[:picture][:tempfile] , because Paperclip received an adapter for File objects, for example this

 user.picture = params[:picture][:tempfile] user.picture_file_name = params[:picture][:filename] # Preserve the original file name 
+2
source

All Articles