Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Accessing an Uploaded File and Saving it to PaperClip

I'm using the following file uploader with Rails 3: https://github.com/blueimp/jQuery-File-Upload

The uploader on the client side is working fine. I can see in the Rails log file that the following is being posted when I upload a file:

Started POST "/attachments/upload" for 127.0.0.1 at Mon Jan 24 14:15:25 -0800 2011
  Processing by AttachmentsController#upload as */*
  Parameters: {"_http_accept"=>"application/javascript", "authenticity_token"=>"F1h9pvCZL9HUgTjwCIAMc%252BW1cYwx7eBOPwThHfbS5ZU%253D", "file"=>#<ActionDispatch::Http::UploadedFile:0x1076a6d48 @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"joecocker.jpg\"\r\nContent-Type: image/jpeg\r\n", @original_filename="joecocker.jpg", @tempfile=#<File:/var/folders/lF/lF0Ne5vGFj44kV54W3zBdU+++TI/-Tmp-/RackMultipart20110124-12264-rbtnth-0>>}

The issue I'm having is I'm unable to save the uploaded file to Paperclip.

I've ried:

@attachment = Attachment.create(:attachment => File.open(params[:file].tempfile.path))
@attachment = Attachment.create(:attachment => params[:file].tempfile.path)

And neither work. Paperclip inserts a file attachment name of "RackMultipart20110124-12264-rbtnth-0"

Any ideas / suggestions on how to save the file to paperclip? thanks

like image 797
AnApprentice Avatar asked Jan 24 '11 22:01

AnApprentice


2 Answers

Just use params[:file] to access the file. No need to do params[:file].tempfile.path. Paperclip takes a full File-like object.

like image 145
Ryan Bigg Avatar answered Nov 15 '22 00:11

Ryan Bigg


it might be the case you have permissions issues. Paperclip by default create a folder with the name system in public folder and there it save all attachment. Check the permission to the your project directory. For testing purpose set it to 777

Secondly you don't need to save the attachments manually. Once you have used paperclip it will automatically save the attached file. To get the things going you need to ensure these steps.

  1. You have added this line to your model , has_attached_file :avatar
  2. You have created paperclip migration and has run the migration You can generate the migration with the following command rails g paperclip "Model Name" avatar (Where avatar will be used to process the attachments.)
  3. In your view page where you are uploading the file use just use f.file_field :avatar
  4. in your show /index file use image_tag :avatar.url(:small), i am assuming image attachment and you have applied style to your image like small thumb etc.

After ensuring above step just run your program it will work.

like image 29
Rufi Avatar answered Nov 15 '22 00:11

Rufi