I'm trying to work around a known issue in Active Storage where the MIME type of a stored file is incorrectly set, without the ability to override it.
https://github.com/rails/rails/issues/32632
This has been addressed in the master
branch of Rails, however it doesn't appear to be released yet (project is currently using 5.2.0). Therefor I'm trying to work around the issue using one of the comments provided in the issue:
Within a new initializer (\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
I'm processing and storing a zip file within a background job using delayed_jobs
. The initializer doesn't appear to be getting called. I have restarted the server. I'm running the project locally using heroku local
to process background jobs.
Here is the code storing the file:
file.attach(io: File.open(temp_zip_path), filename: 'Download.zip', content_type: 'application/zip')
Any ideas why the code above is not working? Active Storage likes to somewhat randomly decide this ZIP file is a PDF and save the content type as application\pdf
. Unrelated, attempting to manually override the content_type
after attaching doesn't work:
file.content_type = 'application/zip'
file.save # No errors, but record doesn't update the content_type
Try with Rails.application.config.to_prepare
in place of after_initialize
initialization event.
more info :