如何通过活动存储将SVG显示为图像

问题描述 投票:4回答:2

我目前在将项目从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-rails image svg rails-activestorage
2个回答
9
投票

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

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


2
投票

SVG被认为是二进制内容类型,因此正将Active Storage SVG链接表示为下载附件链接。您可以在此链接https://github.com/rails/rails/blob/master/activestorage/lib/active_storage/engine.rb上查看所有content_types和限制。

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

© www.soinside.com 2019 - 2024. All rights reserved.