user7055375
user7055375

Reputation:

How do I figure out the mime type without writing a file?

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

Upvotes: 6

Views: 1786

Answers (2)

goose3228
goose3228

Reputation: 371

Assuming you are uploading file via html form, IO object should already have mime type, you can get it like that:

mime = params[:file].content_type

Upvotes: 6

Dipil
Dipil

Reputation: 2708

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

Upvotes: 3

Related Questions