All threads / Carrierwave file extension issue
Ask A Question


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!


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

  storage :fog

    def extension_whitelist

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

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

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


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

What is your issue?

You have it set to only allow png's:

  def extension_whitelist

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.

=> "../large_ac25c7fe-b835-4e7d-adc3-98c92d9f15d8.png"

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

=> "../large_png_ac25c7fe-b835-4e7d-adc3-98c92d9f15d8.png"

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?

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.

Join the discussion

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

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

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

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2022 GoRails, LLC. All rights reserved.