This is with Rails 5 and ruby-filemagic. Currently I'm saving an uploaded image to my database in addition to its mime type. I have this code in my controller
def create
@person = Person.new(person_params)
if @person.image
cur_time_in_ms = DateTime.now.strftime('%Q')
file_location = "/tmp/file#{cur_time_in_ms}.ext"
File.binwrite(file_location, @person.image.read)
fm = FileMagic.new(FileMagic::MAGIC_MIME)
@person.content_type = fm.file(file_location, true)
end
if @person.save
redirect_to @person
else
# This line overrides the default rendering behavior, which
# would have been to render the "create" view.
render "new"
end
end
The thing that bothers me with this approach is taht I have to write a file to the file system before figuring out its mime type. That seems wasteful. How can I figure out the mime type without creating a file first?
Edit: In response to the answer given, I rearranged things, but now the "content_type" becomes "application/x-empty" even when I upload a valid png file. Here's the code
if @person.image
cur_time_in_ms = DateTime.now.strftime('%Q')
file_location = "/tmp/file#{cur_time_in_ms}.ext"
File.binwrite(file_location, @person.image.read)
file = File.open(file_location, "rb")
contents = file.read
# Scale image appropriately
#img = Magick::Image::read(file_location).first
@person.content_type = FileMagic.new(FileMagic::MAGIC_MIME).buffer(@person.image.read, true)
@person.image = contents
FileMagic.new(FileMagic::MAGIC_MIME).file(@person.image.read)
? I'm not familiar with FileMagic but that should work. – Letha@person.image
is already a temporary file. Could you tryfm.file(@person.image.path, true)
? For a true IO data you'd wantfm.buffer
. – Grizzled