简体   繁体   中英

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?

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.

Svg are considered binary content types, so that is why Active storage svg links are represented as download attachment links. You can see all content_types and limitations at this link https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/engine.rb .

More about this limitation and explanation can be found here: http://github.com/jdelStrother/rails/commit/06ab7b27ea1c1ab357085439abacdb464f6742bf . I'll post an issue for this. Maybe they will fix it in the future

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM