Paperclip 2.7
Ruby 1.8.7 Enterprise
Rails 3.1.0
Imagemagick 6.6
When i upload an image im my app, they are correctly processed by imagemagick and they are stored in conrrectly path. But, when i need to take this file to show, is not found.
Saving image:
Started POST "/p" for 177.16.57.105 at Sun Sep 23 23:39:16 -0300 2012
Processing by ProductsController#create as HTML
Parameters: {"commit"=>"Salvar", "authenticity_token"=>"EgBUGfKIIduS2lkl0mh5p27pT0vF0/P8HXO852KHMM8=", "utf8"=>"â", "product"=>{"photo"=>#>, "price"=>"", "name"=>"Brigadeiro de pistache", "product_type"=>"1", "featured"=>"0", "description"=>"Brigadeiro de pistache"}}
[32mCommand[0m :: convert '/tmp/stream20120923-19588-vw8u1s-020120923-19588-3lym39-0[0]' -resize "120x80>" '/tmp/stream20120923-19588-vw8u1s-020120923-19588-3lym39-020120923-19588-16ky3i8-0'
[paperclip] Saving attachments.
[paperclip] saving /home/brigaderiagourmand/apps_rails/site/public/system/photos/24/short/brigadeirocolorido.png
Redirected to http://brigaderiagourmand.com.br/p/24
Completed 302 Found in 257ms
And when i need take the file...
Started GET "/photos/original/missing.png" for 177.16.57.105 at Sun Sep 23 23:39:17 -0300 2012
ActionController::RoutingError (No route matches [GET] "/photos/original/missing.png"):
My model
class Product < ActiveRecord::Base
attr_accessible :name, :description, :price, :photo, :product_type, :featured
attr_accessor :photo_file_name
has_attached_file :photo, :styles => { :thumb => "50x50>", :medium => "280x180>", :large => "585x400>", :short => "120x80>", :original => "200,200>" }
TYPES = ["Belga", "Normal"]
end
Form views
= form_for #product, :html => {:multipart => true} do |f|
= f.file_field :photo
Show view
= image_tag #product.photo.url(:original)
Is the output from processing the image complete?
In your output paperclip only re-sizes to short (120x80>)
Your get request is trying to load the missing.jpg which is a default for image if the the requested couldn't be found. Take a look into /home/brigaderiagourmand/apps_rails/site/public/system/photos/24/ and see if there are the other re-sized photos.
There is a great screencast from Ryan Bates about paperclip
Hope this helps you
Related
please help solve the problem.
using a paperclip I organized upload images. it works.
Now I would like to organize a video upload. I changed this model:
model:
class Video < ActiveRecord::Base
validates :title, presence: true
validates :video, presence: true
belongs_to :user
has_attached_file :video,
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "/images/:style/missing.png"
validates_attachment_content_type :video, :content_type => /\Avideo\/.*\Z/
validates_attachment_file_name :video, :matches => [/3gp\Z/, /mp4\Z/, /flv\Z/]
validate :file_size_validation, :if => "video?"
def file_size_validation
errors[:video] << "should be less than 2MB" if video.size.to_i > 30.megabytes
end
end
video controller:
def create
#video = Video.new(video_params)
if #video.save
#video.update_attributes(user: current_user)
flash[:success] = :video_created
redirect_to #video
else
flash.now[:error] = :user_not_created
render 'new'
end
end
form:
<%= form_for(#video) do |f| %>
<%= f.text_field :title %>
<%= f.file_field :video %>
<%= f.submit %>
<% end %>
after attempting to upload the video I get the console the following error message:
Started POST "/videos" for 127.0.0.1 at 2015-07-23 14:17:32 +0300
Processing by VideosController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"RF3w8PzZ9LZ4pdqRPqRvHMQ+nYDL4om0YHAMlzTm8tf3iFmVmKxXSYKap3C0ogEnOkifm9i01oXs/rTX9zmtPA==", "video"=>{"title"=>"tty", "video"=>#<ActionDispatch::Http::UploadedFile:0x007f6624f10770 #tempfile=#<Tempfile:/tmp/RackMultipart20150723-13428-u7s8i8.flv>, #original_filename="mmm.flv", #content_type="video/x-flv", #headers="Content-Disposition: form-data; name=\"video[video]\"; filename=\"mmm.flv\"\r\nContent-Type: video/x-flv\r\n">}, "commit"=>"Create Video"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1 [["id", 8]]
Command :: file -b --mime '/tmp/c4efd5020cb49b9d3257ffa0fbccc0ae20150723-13428-6gn39i.flv'
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/c4efd5020cb49b9d3257ffa0fbccc0ae20150723-13428-1eailfd.flv[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
Command :: identify -format '%wx%h,%[exif:orientation]' '/tmp/c4efd5020cb49b9d3257ffa0fbccc0ae20150723-13428-1eailfd.flv[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::Errors::NotIdentifiedByImageMagickError: Paperclip::Errors::NotIdentifiedByImageMagickError>
(0.2ms) BEGIN
Command :: file -b --mime '/tmp/c4efd5020cb49b9d3257ffa0fbccc0ae20150723-13428-khstwa.flv'
(0.2ms) ROLLBACK
on screen displays the following error message:
Video Paperclip::Errors::NotIdentifiedByImageMagickError
wherein imageMagik installed in my system:
sudo apt-get install imagemagick
db:
create_table "videos", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "title"
t.integer "user_id"
t.string "video_file_size"
t.string "video_updated_at"
t.string "video_file_name"
t.string "video_content_type"
end
Working with image with paperclip and with video is different.Though the common point is that it will help you tu send the uploaded data to the server but you need to handle it with some processor.Just like you use ImageMagick for images,you should use FFMPEG to encode/decode video.
i will share the code which i usually use for video..but before that ,you must set up ffmpeg to handle all formats of video just like you did for Imagemagick.
here is set up for ffmpeg and dont forget to provide path in environment file using which ffmpeg
you need ffmpeg-paperclip as well for coding/decoding videos.
video.rb
##using s3
##convert the video into mp4 and also get screenshot of video at 5 sec
##add your own formats that you want
has_attached_file :video,
:styles => {
:mp4video => { :geometry => '520x390', :format => 'mp4',
:convert_options => { :output => { :vcodec => 'libx264',
:vpre => 'ipod640', :b => '250k', :bt => '50k',
:acodec => 'libfaac', :ab => '56k', :ac => 2 } } },
:preview => { :geometry => '300x300>', :format => 'jpg', :time => 5 }
},
processors: [:ffmpeg],
:storage => :s3,
:size => { :in => 0..25.megabytes },
:s3_permissions => :public_read,
:s3_credentials => S3_CREDENTIALS
validates_attachment_content_type :video, :content_type => /\Avideo\/.*\Z/
validates_presence_of :video
once you have saved the video,you need to use some plugins to show the video player along with your video in show action.You can use Mediaelement.js(my favorite).Download it,dump it in js/css files accordingly,Include it in application.js and application.css.
in your show.html.erb
##add video tag to show video
<video autobuffer="autobuffer" preload="auto" style="width:100%;height:100%;" controls="controls" width="100%" height="100%" poster="<%= #video.video.url(:preview)%>" >
<source src="<%= #video.video.url%>" />
<%if #video.video.expiring_url(:mp4video).present? %>
<source type="video/mp4" src="<%= #video.video.url(:mp4video)%>" />
<%end%>
</video>
##javascript to handle video player
$('video').mediaelementplayer();
paperclip's processor is designed for images, so it cannot handle videos. You're getting the error saying that ImageMagick did not recognize this file as an image. Fair enough, it's not an image!
Still, you could write a post-processor yourself, and paperclip's github page offers an example of the syntax that would be needed to call a custom processing class:
has_attached_file :scan, :styles => { :text => { :quality => :better } },
:processors => [:ocr]
This defines a variation of the attachment called text that is obtained by processing the uploaded file with a (hypothetical) Paperclip::Ocr class with options hash { :quality => :better }
Choice of the exact conversion tool is up to you, but you do want to make sure that processing is done asynchronously, not inside the usual request-response cycle, you may want to use a background queue like Sidekiq, Que or Rails' (4.2+) ActiveJob.
I am new to paperclip, and I wanted to see how it would work. I generated a simple model Monkey and got the following:
rails g scaffold monkey description age:datetime
rails g paperclip monkey facepic
rake db:migrate
Model
class Monkey< ActiveRecord::Base
has_attached_file :facepic, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
View new/edit
<%= form_for #monkey, :url => monkies_path, :html => { :multipart => true } do |f| %>
...
<div class="field">
<%= f.label :facepic %><br>
<%= f.file_field :facepic %>
</div>
View show
<%= image_tag #monkey.facepic.url %>
Controller
#monkey = Monkey.new(monkey_params)
I can create new monkeys, but the show view doesn't seem to find the uploaded file. I have no error messages, except a routing error to 'missing.png'. There is no trace to the uploaded image. I am using Rails 4.1.6. What am I missing here? How do I troubleshoot this thing? The gem is installed and also imagemagick is installed.
This is what the logs say:
ActionController::RoutingError (No route matches [GET] "/facepics/original/missing.png"):
...
Started GET "/monkies/new" for 127.0.0.1 at 2014-09-19 14:40:22 +0200
Processing by MonkiesController#new as HTML
Rendered monkies/_form.html.erb (4.0ms)
Rendered monkies/new.html.erb within layouts/application (5.0ms)
Completed 500 Internal Server Error in 12ms
ActionView::Template::Error (No route matches {:action=>"show", :controller=>"monkies"} missing required keys: [:id]):
There is no error message displayed however when I create a new monkey... :'(
EDIT:
The Monkey model is created, but the paperclip columns remain empty.
This error clearly show that your images are not getting saved because path and url not specified in your has_attached_file block. It should be like :
has_attached_file :facepic,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename",
:styles => { :medium => "300x300>", :thumb => "100x100>" },
:default_url => "path to default image"
here default_url show image that you want if no image uploaded. For more detail you can go here http://rdoc.info/gems/paperclip/4.2.0/Paperclip/ClassMethods%3ahas_attached_file .
And for other error you can follow this link Paperclip::Errors::MissingRequiredValidatorError with Rails 4
Starting with Paperclip version 4.0, all attachments are required to include a content_type validation, a file_name validation, or to explicitly state that they're not going to have either.
Paperclip raises Paperclip::Errors::MissingRequiredValidatorError error if you do not do any of this.
In your case, you can add any of the following line to your Post model, after specifying has_attached_file :image
Option 1: Validate content type
validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
-OR- another way
validates_attachment :image, content_type: { content_type: ["image/jpg", "image/jpeg", "image/png", "image/gif"] }
-OR- yet another way
is to use regex for validating content type.
Option 2: Validate filename
validates_attachment_file_name :avatar, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]
Option 3: Do not validate
If for some crazy reason (can be valid but I cannot think of one right now), you do not wish to add any content_type validation and allow people to spoof Content-Types and receive data you weren't expecting onto your server then add the following:
do_not_validate_attachment_file_type :image
Note:
Specify the MIME types as per your requirement within content_type/ matches options above. I have just given a few image MIME types for you to start with.
Reference:
Refer to Paperclip: Security Validations, if you still need to verify. :)
For details you can go to This question
I am sorry to say that my problem eventually was a bunch of things:
Had to add :facepic to the strong params
Had to add validations of content type to the model
Paperclip has a dependency... the file-command, which isn't shipped on Windows.
which can be downloaded here: http://sourceforge.net/projects/gnuwin32/?source=typ_redirect
After all three, it works like a charm!
Thank you all!
I'm using Paperclip with my Rails 3.0 app in order to add an avatar to a user, and it won't save the image because the paths are off. Heres what I get:
Started GET "/profilepics/small/missing.png" for 127.0.0.1 at 2012-04-11 23:38:29 -0700
ActionController::RoutingError (No route matches "/profilepics/small/missing.png"):
My user model has:
has_attached_file :profilepic, :styles => { :small => "150x150>" }
What should I put for :path => & :url => ?
Form looks like :
<% form_for #user, :html => { :multipart => true } do |f| %>
<%= f.file_field :profilepic %>
<% end %>
Logs look like :
Started GET "/system/profilepics/small/missing.png" for 127.0.0.1 at 2012-04-12 00:33:51 -0700
ActionController::RoutingError (No route matches "/system/profilepics/small/missing.png"):
Rendered /usr/lib/ruby/gems/1.9.1/gems/actionpack-3.0.12/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (1.2ms)
See my sample:
has_attached_file :avatar, :styles => { :thumb => "50x50#", :large => "1000x1000>", :medium => "200x200#" },
:default_url => "/system/avatars/:style/missing.png",
:url => "/system/:attachment/:id/:style_:filename",
:path => ":rails_root/public/system/:attachment/:id/:style_:filename"
:default_url - is the path for the default image, when the user didn't upload any avatar
"#" - this symbol is to crop image
then you can show your images as such:
<%=image_tag(#user.avatar.url(:thumb))%>
<%=image_tag(#user.avatar.url(:medium))%>
Works now!!!
For people struggling with the same issue, here's a few important things to ALWAYS make sure and check:
In your form, always specify { :multipart => true } otherwise, the form won't accept file attachments.
<%= form_for #user, :html => **{ :multipart => true }** do |f| %>
In your user.rb (or whatever model you want to add attachments to ), make attr_accessible :photo (or whatever you name your attachment)
ALWAYS restart your server after installing a new Gem.
:) Thanks guys!!!!
There is no need to given url and path option if you simply want to display an image.
Use this line in show page and it will display image...
<%=image_tag(#user.profilepic.url(:small))%>
And enjoy..............
My model
class Article < ActiveRecord::Base
LOGO_TYPES = ['image/jpeg', 'image/png', 'image/gif']
VALID_LOGO_MESSAGE = 'Please attach a valid picture file containing your organization logo. Valid formats are JPG, PNG, and GIF'
has_attached_file :logo, :content_type => LOGO_TYPES,
:path => ":rails_root/app/assets/images/uploads/articlelogos/:id/:style/:basename.:extension",
:url => "/assets/uploads/articlelogos/:id/:style/:basename.:extension"
validates_attachment_content_type :logo, :content_type => LOGO_TYPES, :message => VALID_LOGO_MESSAGE
validates_attachment_size :logo, :less_than => 1.megabytes
end
When I try to upload a valid, 6k .gif logo using Paperclip, I get:
Logo_file_size file size must be between 0 and 1024 bytes
Logs as request hits :
Started PUT "/articles/74" for x.x.x.x at 2012-01-15 17:44:20 -0600
Processing by ArticlesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"uI+OXmV3B/crOrUopbBxpRs242PzMVJY1uM/QBnHdlE=", "article"=>{"logo"=>#<ActionDispatch::Http::UploadedFile:0x000000081d70b0 #original_filename="test_logo.gif", #content_type="image/gif",
#headers="Content-Disposition: form-data; name=\"article[logo]\"; filename=\"test_logo.gif\"\r\nContent-Type: image/gif\r\n",
#tempfile=#<File:/tmp/RackMultipart20120115-30606-1wwkr21>>}, "commit"=>"Upload Now", "id"=>"74"}
And I added some debugging to show the tempfile
params[:article][:logo].inspect: #<File:/tmp/RackMultipart20120115-30606-1wwkr21>>
params[:article][:logo].size: 6531
So it is clearly being stored on the server, but Paperclip is failing to check the size properlly.
This works on my local Mac in development mode, but fails on production under Ubuntu.
Any ideas? Thanks!
Update - removing size validation enables the file to be uploaded and stored as usual
I have set up Paperclip and ImageMagick successfully on my system, and files are uploading correctly, being resized, and and being saved into the right folders.
I try to display those images in my view:
<%= image_tag #customer.logo.url(:medium) %>
No image is displayed. When I go to the image's direct url I get:
Routing Error
No route matches "/images/assets/logos/1/medium/corplogo.jpg" with {:method=>:get}
This is a local server still in development and running on Windows. My forms are multipart:
<% form_for #customer, :url => {:action => "update", :id => #customer}, :html => {:multipart => true, :id => "myform"} do |f| %>
------ Dev Server ------
Processing ApplicationController#index (for 127.0.0.1 at 2010-09-27 04:38:33) [G
ET]
Parameters: {"1285570273"=>nil}
ActionController::RoutingError (No route matches "/images/assets/logos/1/medium/corplogo.jpg" with {:method=>:get}):
haml (3.0.15) rails/./lib/sass/plugin/rack.rb:41:in `call'
Rendering rescues/layout (not_found)
------ Model ------
has_attached_file :logo,
:url => "assets/logos/:id/:style/:basename.:extension",
:path => ":rails_root/public/assets/logos/:id/:style/:basename.:extension",
:styles => {:medium => "300x300>", :thumb => "100x100>" }
I found the answer to the problem, and it lies with the url declaration in the model.
Instead of:
:url => "assets/logos/:id/:style/:basename.:extension"
it should be:
:url => "/assets/logos/:id/:style/:basename.:extension"
I got this error using the "webrick" server. and I check all the file access permission on my "public/system" folder, they are normal.
finally I switched to apache/passenger, it works, the images are displayed correctly.