Misha Moroshko
Misha Moroshko

Reputation: 171399

How to open a picture in a browser rather than download it when the picture is hidden behind Controller?

When a picture is located in the public area, e.g. /public/temp, clicking the following thumbnail opens the original image (in the same window):

<a href="/temp/original.jpg">
  <img src="/temp/thumb.jpg" />
</a>

However, when a picture is hidden behind Controller, and the HTML looks like:

<a href="/assets/1/original">
  <img src="/assets/1/thumb" />
</a>

clicking the thumbnail downloads the original picture to my computer.

Is that possible in this case to enforce the original picture to be opened in the browser (like it is done when the picture is in the public area) ?

Here is the relevant code:

class AssetsController < ApplicationController
  def download
    head(:not_found) and return unless file = Asset.find_by_id(params[:id])
    path = file.asset.path(params[:style])
    head(:bad_request) and return unless File.exist?(path)
    send_file(path, { :type => File.mime_type?(path) })
  end    
end

(mime_type? comes from the mimetype_fu gem)

# config/routes.rb
match "/assets/:id/:style" => "assets#download"

Upvotes: 2

Views: 571

Answers (1)

Misha Moroshko
Misha Moroshko

Reputation: 171399

I found the answer:

send_file(path, { :type => File.mime_type?(path), :disposition => 'inline' })

Upvotes: 2

Related Questions