Ask A Question

Notifications

You’re not receiving notifications from this thread.

Carrierwave file extension issue

Thomas Bush asked in Gems / Libraries

Carrierwave is converting and uploading image files with proper extensions to S3, but storing all in db as .png extension when accessing the .url method for versions.

The file name and secure token methods are taken straight from the carrierwave wiki

Any help would be greatly appreciated, thanks!

Uploader

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  storage :fog

    def extension_whitelist
      %w(png)
  end

  def filename
    "#{secure_token}.#{file.extension}" if original_filename.present?
  end

  version :large do
    process resize_and_pad: [650, 650, '#FFFFFF', 'Center'], convert: :jpg
  end

  version :large_png do
    process resize_to_fit: [650, 650]
  end

  protected

  def secure_token
    var = :"@#{mounted_as}_secure_token"
    model.instance_variable_get(var) || model.instance_variable_set(var, SecureRandom.uuid)
  end
end
Reply

What is your issue?

You have it set to only allow png's:

  def extension_whitelist
      %w(png)
  end
Reply

It sounds like I misunderstood the extension_whitelist method, I thought this was similar to a frontend form validation -- my intention is to only allow the user to send a png, as I need to use transparent backgrounded images in certain places, than generate the jpgs as these are used most places.

Regardless, removing the whitelist entirely yeilds the same result -- correct images in s3, but incorrect images in db.

instance.file_name.large.url 
=> "../large_ac25c7fe-b835-4e7d-adc3-98c92d9f15d8.png"

The actual file for the above renders a 404 as the file is a .jpg in S3

instance.file_name.large_png.url
=> "../large_png_ac25c7fe-b835-4e7d-adc3-98c92d9f15d8.png"
Reply

In that case, you're gonna want to change your method for the filename to use .jpg instead of the original extension:

  def filename
    "#{secure_token}.jpg" if original_filename.present?
  end

You might want to add a conditional to do this only for a specific version (the one that you converted to jpg) and use the original extension as necessary for the rest.

Reply
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.