繁体   English   中英

如何使用 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 添加到我的 gemfile 中。 对于 png 和 jpg 文件,它工作得很好。

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

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

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

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 我会为此发布一个问题。 也许他们将来会修复它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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