fix: send images with correct content types

This commit is contained in:
Neetpone 2024-04-13 18:20:41 -04:00
parent b9872ba287
commit 95a65e9a6e
3 changed files with 17 additions and 7 deletions

View file

@ -25,6 +25,9 @@ gem 'model-msearch'
gem 'puma', '~> 5.0'
gem 'sidekiq'
# Other stuff
gem 'marcel'
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: %i[ mingw mswin x64_mingw jruby ]

View file

@ -306,6 +306,7 @@ DEPENDENCIES
elasticsearch-model
fancy_searchable!
kaminari
marcel
model-msearch
pg (~> 1.1)
puma (~> 5.0)

View file

@ -17,17 +17,23 @@ class ImagesController < ApplicationController
hash = Digest::SHA256.hexdigest(url)
path = Rails.root.join('public', 'cached-images', hash + ext)
our_url = "/cached-images/#{hash}#{ext}"
content_type = nil
if File.exist? path
redirect_to our_url
return
content_type = Marcel::MimeType.for Pathname.new(path)
else
content_type, body = fetch_image uri
File.binwrite path, body
end
File.binwrite(
path,
Net::HTTP.get(parsed)
)
send_file path, disposition: :inline, content_type: content_type
end
redirect_to our_url
private
def fetch_image(uri)
response = Net::HTTP.get_response(uri)
[response['Content-Type'], response.body]
end
end