Abdul-Rahman Ahmad
Abdul-Rahman Ahmad

Reputation: 163

Paperclip: Saving Base64 encoded file, saved without extension

I'm trying to save Base64 encoded string using paperclip on rails, but the resulting file has no extension

The encoded string is as follows:

{"model"=>{"photo"=>"data:image/jpeg;base64,/9j..}

The paperclip configurations

has_attached_file :photo,
                  :styles => { medium: "380x380>", small: "200x200>", thumb: "100x100>" },
                :path => ":rails_root/model/:style/:id.:extension",
                :url => "/object_image/model/:style/:id.:extension",                    
                  :default_url => "/images/default-avatar.png"

validates_attachment_content_type :photo,
                                  :content_type => ["image/jpg", "image/jpeg",
                                                    "image/png", "image/gif"]

The resulting file is : 1.

Any help is appeciated. Thank you

Upvotes: 0

Views: 700

Answers (1)

user773277
user773277

Reputation: 118

tries to set back the extension using the image's content type

tempfile = self.image.queued_for_write[:original]
unless tempfile.nil?
  extension = File.extname(tempfile.original_filename)
  if !extension || extension == ''
    mime = tempfile.content_type
    ext = Rack::Mime::MIME_TYPES.invert[mime]
    self.image.instance_write :file_name, "#{tempfile.original_filename}#{ext}"
  end
end

special thanks to stackoverflow.

Upvotes: 2

Related Questions