我正在尝试解决Active Storage中的一个已知问题,在该问题中,存储文件的MIME类型设置错误,无法覆盖它。
https://github.com/rails/rails/issues/32632
此问题已在Rails的master
分支中解决,但是它似乎尚未发布(项目当前正在使用5.2.0)。因此,我正在尝试使用问题中提供的评论之一来解决该问题:
在新的初始化程序(\config\initializers\active_record_fix.rb
)中:
Rails.application.config.after_initialize do
# Defeat the ActiveStorage MIME type detection.
ActiveStorage::Blob.class_eval do
def extract_content_type(io)
return content_type if content_type
Marcel::MimeType.for io, name: filename.to_s, declared_type: content_type
end
end
end
我正在使用delayed_jobs
在后台作业中处理和存储一个zip文件。初始化程序似乎没有被调用。我已经重新启动服务器。我正在使用heroku local
在本地运行项目以处理后台作业。
以下是存储文件的代码:
file.attach(io: File.open(temp_zip_path), filename: 'Download.zip', content_type: 'application/zip')
有什么想法为什么上面的代码不起作用? Active Storage喜欢以某种随机方式将这个ZIP文件确定为PDF,然后将内容类型另存为application\pdf
。不相关,尝试在附加后手动覆盖content_type
不起作用:
file.content_type = 'application/zip'
file.save # No errors, but record doesn't update the content_type
答案 0 :(得分:1)
尝试使用Rails.application.config.to_prepare
代替after_initialize
初始化事件。
更多信息: