首页 > 解决方案 > 如何使用 Active Storage 将 SVG 显示为图像

问题描述

我目前在将我的项目从 Paperclip 移动到 ActiveStorage 时遇到问题。更准确地说,我在 ActiveStorage 和存储 svg 图像方面遇到问题。

我知道 svg 文件是图像,但它们不是可变图像。由于某种原因,活动存储正在创建下载链接,这就是为什么 svg 文件未在浏览器中显示的原因。

活动存储忽略 content_type 例如(来自我的种子):

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' )

尽管“iamge/svg+xml”是有效的图像类型,但活动存储属于“application/octet-stream”。我已经从我的模型中删除了所有验证,并将 miniMagick gem 添加到我的 gemfile 中。使用 png 和 jpg 文件,它可以完美运行。

我的问题是,我做错了什么?ActiveStorage 甚至支持 svg 文件吗?

标签: ruby-on-railsimagesvgrails-activestorage

解决方案


将此代码添加到您的 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')

您当然可以删除评论:)。希望能帮助到你。


推荐阅读