Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display SVG as images with Active Storage

I'm currently having issues with moving my project from Paperclip to ActiveStorage. More precisely I'm having issues with ActiveStorage and storing svg images.

I know that svg files are images, but they are not variable images. Because of that Active storage for some reason is creating download links and that is why svg files are not shown in browser.

Active storage is neglecting content_type for example (from my seeds):

job = Job.create(career.except(:icon, :og_image))
job.icon.attach(io: career[:icon], filename: 
File.basename(career[:icon].path), content_type: 'image/svg+xml' )
job.og_image.attach(io: career[:og_image], filename: 
File.basename(career[:og_image].path), content_type: 'image/png' )

Active storage falls to 'application/octet-stream' although 'iamge/svg+xml' is valid image type. I have removed all validations from my models and I have miniMagick gem added to my gemfile. With png and jpg files it is working perfectly.

My question is, what am I doing wrong? And does ActiveStorage even have support for svg files?

like image 459
Visko Plenković Avatar asked Dec 05 '18 09:12

Visko Plenković


1 Answers

Add this code to your config/application.rb:

# Hack for allowing SVG files. While this hack is here, we should **not**
# allow arbitrary SVG uploads. https://github.com/rails/rails/issues/34665

ActiveStorage::Engine.config
.active_storage
.content_types_to_serve_as_binary
.delete('image/svg+xml')

You can delete comments of course :). Hope it helps.

like image 162
Visko Plenković Avatar answered Sep 19 '22 09:09

Visko Plenković