carrierwave
Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks
carrierwaveuploader/carrierwave · GitHub carrierwave - classier solution for file uploads for rails, sinatra and other ruby web frameworks
I am trying to display the filename of a Carrierwave attachment in a Rails erb template. The following does not work:
<%= @page.form.filename %>
This seems in line with the documentation. Is some additional step needed?
My page model looks like this:
class Page < ActiveRecord::Base
mount_uploader :form, FormUploader
end
The form uploader looks like this:
class FormUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(pdf)
end
end
Source: (StackOverflow)
I'm trying to use this code in my uploader
version :thumb do
process :scale => [50, 50]
end
and I get an error saying
undefined method `scale' for #<#<Class:0x235b680>:0x0fb4c8>
I'm using Carrierwave with MiniMagick. How can I fix this error?
Source: (StackOverflow)
I am not sure how to configure the environment such that Carrier Wave will use the local file storage when running the app locally (development) and s3 after i load to heroku (production)
in Development storage :file
in Production storage :s3
Source: (StackOverflow)
Let's say my model has an image with :thumb
and the client wants :tiny
and :nano
thumbnails.
How do I reprocess all the existing images using a rake task?
I've found a rask that I thought would do it https://gist.github.com/777788 but it's giving me errors.
Source: (StackOverflow)
I have a simple model that mounts a Carrierwave uploader. Everything works fine in development, but I get an undefined method "image_will_change!" error on heroku.
class Receipt < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
class ImageUploader < CarrierWave::Uploader::Base
storage :fog
def store_dir
"receipts/saved"
end
end
I have the cache_dir set appropriately as well according to the Carrierwave Wiki.
receipt.image = File.open "public/images/test.jpg" #works fine in development, fails in heroku
Source: (StackOverflow)
I'm using RMagick and want my images to be resized to a fixed width of 100px, and scale the height proportionally. For example, if a user were to upload a 300x900px, I would like it to be scaled to 100x300px.
Source: (StackOverflow)
In our latest application we need to process some uploads, I've worked with paperclip before and everything just works! but we're giving carrierwave a try, it looks promising but, I can't find how to validate the size of an attachment, it seems like the documentation doesn't have any information about it, should we add it manually to the model via a custom validator?
Thanks in advance!
Source: (StackOverflow)
Before I go into detail I'll get right to the point: has anyone figured out a way to get Carrierwave to save files with their names as a timestamp or any arbitrary string that is unique to each file?
By default Carrierwave saves each file and its alternate versions in its own directory (named after the model ID number). I'm not a fan of this because instead of one directory with 1,000, for the sake of using a large round number, files (in my case pictures) in it we get one directory with 1,000 subdirectories each with one or two files. Yuck.
Now, when you override your Uploader's store_dir
method to be something like the following:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}"
end
you end up with the exact behavior that I want. All the files (pictures) go into one big happy folder. No more subfolders that stick around when the object gets deleted.
There's only one problem. File collisions. If you upload delicious_cake.jpg twice the second one will overwrite the first even if they are two different pictures of delicious cake! That's clearly why the store_dir
method has the extra /#{model.id}
tacked on the end of the value it returns.
So, what to do? After reading around a bit I discovered that in the generated uploader file there is an apparent solution commented out.
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
After a little bit of searching I found someone who had done the following
def filename
@name ||= "#{secure_token}.#{file.extension}" if original_filename
end
This got me thinking, why not just do this
def filename
@name ||= "#{(Time.now.to_i.to_s + Time.now.usec.to_s).ljust(16, '0')}#{File.extname(original_filename)}"
end
That's when things got horribly broken. The problem with this is that filename
apparently gets called for each version of the file so we end up with file names like 1312335603175322.jpg and thumb_1312335603195323.jpg. Notice the slight difference? Each file name is based on the time when filename
was called for that particular version. That won't do at all.
I next tired using model.created_at
for the basis of the timestamp. Only one problem, that returns nil for the first version since it hasn't been put in the database yet.
After some further thinking I decided to try the following in my pictures controller.
def create
if params[:picture] and params[:picture][:image]
params[:picture][:image].original_filename = "#{(Time.now.to_i.to_s + Time.now.usec.to_s).ljust(16, '0')}#{File.extname(params[:picture][:image].original_filename)}"
end
...
This overrides the original_filename property before Carrierwave even gets to it making it be a timestamp. It does exactly what I want. The original version of the file ends up with a name like 1312332906940106.jpg and the thumbnail version (or any other version) ends up with a name like thumb_1312332906940106.jpg.
But, this seems like an awful hack. This should be part of the model, or better yet part of the uploader mounted onto the model.
So, my question is, is there a better way to achieve this? Did I miss something crucial with Carrierwave that makes this easy? Is there a not so obvious but cleaner way of going about this? Working code is good, but working code that doesn't smell bad is better.
Source: (StackOverflow)
I have a small Rails 3.2.1 app that uses CarrierWave 0.5.8 for file uploads to S3 (using Fog)
I want users to be able to select some images that they'd like to download, then zip them up and send them a zip. Here is what I've come up with:
def generate_zip
#A collection of Photo objects. The Photo object has a PhotoUploader mounted.
photos = Photo.all
tmp_filename = "#{Rails.root}/tmp/" << Time.now.strftime('%Y-%m-%d-%H%M%S-%N').to_s << ".zip"
zip = Zip::ZipFile.open(tmp_filename, Zip::ZipFile::CREATE)
zip.close
photos.each do |photo|
file_to_add = photo.photo.file
zip = Zip::ZipFile.open(tmp_filename)
zip.add("tmp/", file_to_add.path)
zip.close
end
#do the rest.. like send zip or upload file and e-mail link
end
This doesn't work because photo.photo.file returns an instance of CarrierWave::Storage::Fog::File instead of a regular file.
EDIT: The error this leads to:
Errno::ENOENT: No such file or directory - uploads/photos/name.jpg
I also tried the following:
tmp_filename = "#{Rails.root}/tmp/" << Time.now.strftime('%Y-%m-%d-%H%M%S-%N').to_s << ".zip"
zip = Zip::ZipFile.open(tmp_filename, Zip::ZipFile::CREATE)
zip.close
photos.each do |photo|
processed_uri = URI.parse(URI.escape(URI.unescape(photo.photo.file.authenticated_url)).gsub("[", "%5B").gsub("]", "%5D"))
file_to_add = CarrierWave::Uploader::Download::RemoteFile.new(processed_uri)
zip = Zip::ZipFile.open(tmp_filename)
zip.add("tmp/", file_to_add.path)
zip.close
end
But this gives me a 403. Some help would be greatly appreciated.. It probably is not that hard I'm just Doing it Wrong™
Source: (StackOverflow)
I have Rails 3
Carrierwave 0.5.4
//app/uploaders/fasta_uploader.rb
class FastaUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
'public/data/01_fasta'
end
end
//migration
class AddFileUpToCvits < ActiveRecord::Migration
def self.up
add_column :cvits, :fasta, :string
end
def self.down
remove_column :cvits, :fasta
end
end
//app/models/cvit.rb
class Cvit < ActiveRecord::Base
attr_accessible :fasta
mount_uploader :fasta, FastaUploader
end
//form
<%= form_for(@cvit, :html => {:multipart => true, :onsubmit => "return ray.ajax()" }) do |f| %>
...
...
<%= f.file_field :fasta %><br></br>
<div class="actions">
<%= f.submit "Submit"%>
</div>
<% end %>
I get this error: uninitialized constant Cvit::FastaUploader
Any suggestions???
Source: (StackOverflow)
I'm making a rails 3.1 app using carrierwave to upload files to aws s3. I've followed the instructions on the carrierwave github repository and am now able to upload files to my aws bucket. It's the testing that got me stuck. Over the last two days I've been googling and revising, using all the other Q&A's I've found but am finally crying 'mama.' Here's what I've got:
/app/uploaders/image_file_uploader.rb
storage :fog
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
/config/initializers/carrierwave.rb
if Rails.env.test? or Rails.env.cucumber?
CarrierWave.configure do |config|
config.storage = :file
config.enable_processing = false
end
end
/spec/uploaders/image_file_uploader_spec.rb
require 'spec_helper'
require 'support/fog_helper'
require 'carrierwave/test/matchers'
describe ImageFileUploader do
include CarrierWave::Test::Matchers
before do
ImageFileUploader.enable_processing = true
@user = Factory(:user, :email => "photo_taker@example.edu")
@uploader = ImageFileUploader.new(@user, Factory(:image))
@uploader.store!(File.open("#{Rails.root}/tmp/uploads/#{Rails.env}/images/"))
end
after do
@uploader.remove!
ImageFileUploader.enable_processing = false
end
context 'the tiny version' do
it "should scale down a landscape image to be exactly 50 by 50 pixels" do
@uploader.tiny.should have_dimensions(50, 50)
end
end
spec/factories.rb
Factory.define :image do |image|
include ActionDispatch::TestProcess
image.date_taken "Sun, 09 Oct 2011"
image.time_taken "2000-01-01 03:41:00 UTC"
image.image_file fixture_file_upload('spec/support/test_images/audi.png', 'image/png')
image.taken_by "John Doe"
image.collection "N/A"
image.comments "Beautiful day!"
image.association :user
end
While my /public/uploads/tmp/ is getting filled up with 'tiny' (and other versions) of the images whose generation I am testing, the tests continue to fail with the following error message:
1) ImageFileUploader the tiny version should scale down a landscape image to be exactly 50 by 50 pixels
Failure/Error: @uploader = ImageFileUploader.new(@user, Factory(:image))
Excon::Errors::NotFound:
Expected(200) <=> Actual(404 Not Found)
request => {:expects=>200}
response => #<Excon::Response:0x0000010569f928 @body="", @headers={}, @status=404>
# ./spec/uploaders/image_file_uploader_spec.rb:11:in `block (2 levels) in <top (required)>'
I know that the above means that rspec isn't finding my testing bucket. Anyone have any thoughts about what I'm doing wrong?
would be super grateful for any new leads.
UPDATE: 10/11/11
The file upload works but I've stalled in figuring out how to get test involving the images to pass. In the short term, I will use a placeholder image as I flesh out the rest of my app and return to this later. I'll post a further update once I figure this out. (Do leave any thoughts if you have any insights, however.)
Source: (StackOverflow)
I have a post model and a podcast model. Both models have an attribute titled: image. I'm using one Carrierwave uploader (named ImageUploader) to handle both models. I have two questions before I go into production.
Dumb question:
Is it ok to use the same uploader for two different models when they both have the same attribute name for their file attachements? sorry if it seems obvious
Main question:
I want to create three versions of each blog post image (thumb, large, sepia) and only 1 version of each podcast image (thumb).
Do I need to use two uploaders now or can I namespace with the one that I'm already using?
Again it probably seems obvious. I could probably have written the second uploader in the time its taken me to ask these questions
Source: (StackOverflow)
This question already has an answer here:
Hello i need to build up Factory for my model, for example
Factory.define :farm do |f|
f.name { Factory.next :name }
f.harvest '3'
f.offers 'Random'
f.latitude '43'
f.longitude '-70'
f.about 'We rocks!'
f.logo { Factory.next :logo } # this doesn't work
end
For now im just pass string "#{n}.jpg" into my logo field and this dont work, how to evalute this field? Im using CarrierWave for uploading.
Source: (StackOverflow)
I just wanted to know how one would go about uploading a remote file url using Carrierwave in the Rails console.
I tried the following without any luck. I presume it's not processing the Uploader?
user = User.first
user.remote_avatar_url = "http://www.image.com/file.jpg"
user.save
Many thanks
Source: (StackOverflow)