How do I get a ".doc" file extension given my "application/msword" mime type in Rails?

1.1k views Asked by At

I’m using Rails 5. I store file data and the mime type in a PostGres database. Then I use

extension = Rack::Mime::MIME_TYPES.invert[mime_type]

to get a file extension when I return the data in a file to the user. However, if my mime type is

application/msword

The above returns “.dot” and I see this causing confusion with my unsophisticated user base because they are more used to a “.doc” extension. Is there a different mime type I can use that will give back a “.doc” extension or a different function I can use to convert mime types?

2

There are 2 answers

0
Alex Kojin On BEST ANSWER

".dot" file extension has same mime type, it means word microsoft template.

All mime types are sorted alphabetically and you need always return first. Like this

Rack::Mime::MIME_TYPES.rassoc(mime_type).try(:first)
0
Karthick Nagarajan On

Try this gem which will allow you to create word document from HTML.

As per their document,

For htmltoword version >= 0.2 An action controller renderer has been defined, so there's no need to declare the mime-type and you can just respond to .docx format. It will look then for views with the extension .docx.erb which will provide the HTML that will be rendered in the Word file.

# On your controller.
respond_to :docx

# filename and word_template are optional. By default it will name the file as your action and use the default template provided by the gem. The use of the .docx in the filename and word_template is optional.
def my_action
  # ...
  respond_with(@object, filename: 'my_file.docx', word_template: 'my_template.docx')
  # Alternatively, if you don't want to create the .docx.erb template you could
  respond_with(@object, content: '<html><body>some html</body></html>', filename: 'my_file.docx')
end

def my_action2
  # ...
  respond_to do |format|
    format.docx do
      render docx: 'my_view', filename: 'my_file.docx'
      # Alternatively, if you don't want to create the .docx.erb template you could
      render docx: 'my_file.docx', content: '<html><body>some html</body></html>'
    end
  end
end