How to determine mime type without writing a file?

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 # This line overrides the default rendering behavior, which # would have been to render the "create" view. render "new" end end 

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 # 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 
+5
source share
2 answers

Assuming you upload the file via the html form, the IO object should already have a mime type, you can get it like this:

 mime = params[:file].content_type 
+3
source

Try using the buffer method instead of ie FileMagic.new(FileMagic::MAGIC_MIME).buffer(@person.image.read, true)

+3
source

Source: https://habr.com/ru/post/1274779/


All Articles