This is with Rails 5 and ruby-filemagic. I am currently saving the uploaded image to my database in addition to the MIME type. I have this code in the 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
What bothers me with this approach is that I have to write the file to the file system before figuring out its mime type. It seems wasteful. How to determine the mime type without creating a file?
Edit: In response to the provided answer, I rebuilt things, but now "content_type" becomes "application / x-empty", even when I upload a valid png file. Here is 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
user7055375
source share