如何使用 Active Storage 将 SVG 显示为图像

How to display SVG as images with Active Storage

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

我知道svg文件是图片,但不是可变图片。由于某种原因,Active storage 正在创建下载链接,这就是 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 添加到我的 gem 文件中。对于 png 和 jpg 文件,它工作得很好。

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

Svg 被认为是二进制内容类型,这就是为什么 Active storage svg links 被表示为下载附件 links。您可以在此 link https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/engine.rb.

查看所有 content_types 和限制

有关此限制和解释的更多信息,请参见此处:http://github.com/jdelStrother/rails/commit/06ab7b27ea1c1ab357085439abacdb464f6742bf。我会 post 为此提出一个问题。也许他们将来会修复它

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

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