Kevin Brown
Kevin Brown

Reputation: 12650

Rails: Refile for documents to download

Using the refile gem, I have uploaded documents (.pdf, .docx, .pptx, etc.). Uploading is fine. When I use attachemnt_url, it produces something like /attachments/...234jksdf2.../document. When I click the link_to, it downloads the document without an extension.

What's happening to make it operate this way? How can I restore my file type sanity?

Upvotes: 0

Views: 548

Answers (2)

Kevin Brown
Kevin Brown

Reputation: 12650

This is what ended up being the correct solution for me.

link_to "Download file", attachment_url(@document, :file, format: @document.file_extension)

def file_extension 
    require 'rack/mime'   
    Rack::Mime::MIME_TYPES.invert[document_content_type].split('.').last 
end

Upvotes: 0

Wei Jia Chen
Wei Jia Chen

Reputation: 174

I was trying to address the exact same issue, this is one approach I tried:

Refile allows you to save additional metadata such as the content_type: https://github.com/refile/refile#additional-metadata. The resulting file content type will be saved as something like "image/png" or "application/pdf".

We can then apply something like

link_to "Download file", attachment_url(@document, :file, format: @document.file_extension)

Whereby

in document.rb

def file_extension
    file_content_type.split("/").last.to_sym
end

The only issue is that this doesn't automatically downloads the file, but rather opens it in a new page where you can then download the file. Still looking for better alternatives!

Upvotes: 1

Related Questions