rails+sinatra sent image

Hi! I have simple rails application - users with name and avatar and in sinatra I want to create new user.

form for new user

<form action="/users/create" enctype="multipart/form-data" method="post">   <p>     <label for="name">Name: </label>     <input type="text" id="name" name="user[name]" >   </p>   <p>     <label for="avatar">Avatar: </label>     <input type="file" id="avatar" name="avatar" >   </p>     <input type="submit" name="Commit" value="Create"> </form>

My action in sinatra

  post '/users/create' do     RestClient.post("http://localhost:3000/users&quot;, :user=>params['user'])     redirect '/users'   end

I would like to sent file to server in this action.

So the question is: How to sent file as a param to server ? I'm using mozilla firefox 3.6 so I can't get full file path to read it

Looks like you can pass a :multipart option to RestClient to tell it that the post should be multipart.


I tried next

post '/users/create' do   RestClient.post("http://localhost:3000/users&quot;, :user=>params['user'], :avatar=>File.read("/home/qwerty1/Desktop/client/views/images.jpeg"), :multipart=>true)   redirect '/users' end

I tried next

post '/users/create' do RestClient.post("http://localhost:3000/users&quot;, :user=>params['user'], :avatar=>File.read("/home/qwerty1/Desktop/client/views/images.jpeg"), :multipart=>true) redirect '/users' end


require 'paperclip' class User < ActiveRecord::Base has_attached_file :avatar, :styles=>{:thumb=>"100x100", :medium=>"200x200"} # validates_attachment_presence :avatar end

but id didn't sent any image to server

Am I doing something wrong ?

Did you try setting a breakpoint in your rails app to see that the image was being received properly. Does paperclip expect the name of the uploaded file (which you aren't currently transmitting) to have an acceptable extension or for the content type to be set ?


Solved :slight_smile:

#POST create   post '/users/create' do     f = File.new("temp#{params[:user][:login]}.jpg", "w")     t = params[:avatar][:tempfile]     while c = t.gets do       f.puts(c)     end     f.close     RestClient.post("http://localhost:3000/users&quot;,:user=&gt;\{ :login=>params[:user][:login],                                                            :email=>params[:user][:email],                                                            :name=>params[:user][:name],                                                            :avatar=>File.new("temp#{params[:user][:login]}.jpg")},                                                   :multipart=>true)     File.delete("temp#{params[:user][:login]}.jpg")     redirect '/users'   end