hanami/controller

#send_file doesn't send pdf's correctly

aarondufall opened this issue · 1 comments

I'm trying to use #send_file to send a pdf document to the browser with the intention that the pdf will be open in the browser window. All I end up with is a gray dot.

image

I also tried using #send_file_unsafe and got the same behavior.

Here is a code sample that will cause the problem.

require 'aws-sdk'
module Web::Controllers::Files
  class Show
    include Web::Action

    expose :files

    def call(params)
      file = db[:files].where(file_id: params[:id]).first
      key = file[:key]
      bucket = file[:bucket]
      region = file[:region]
      filename = file[:name]


      s3 = Aws::S3::Resource.new(region: region)

      # Create the object to retrieve
      obj = s3.bucket(bucket).object(key)

      uri = ::File.join(Dir.pwd,"public",Date.today.to_s, params[:id] ,filename)
      dirname = ::File.dirname(uri)

      unless ::File.directory?(dirname)
        FileUtils.mkdir_p(dirname)
      end

      obj.get(response_target: uri)

      send_file ::File.join(Date.today.to_s, params[:id] ,filename)
    end

    def db
      @db ||= Sequel.postgres('file_transfer', host:'localhost', user: 'event_source')
    end
  end
end

I also experimented with the headers to see If that would help.

self.headers.merge!({
  'Content-Type' => 'application/pdf',
  'Content-Disposition' => 'inline',
  'filename' => filename })

Hi @aarondufall

Thanks for use Hanami ;) This problem is caused because of Content Security Police header, we have security as first class citizen.

We use CSP values by default, you can check the values generated: https://github.com/hanami/hanami/blob/master/lib/hanami/generators/app/application.rb.tt#L201-L251

The header you have to change is object-src 'none' to object-src 'self' (check is this is the right value for you, but it works) and then the browser will render the pdf.

Cheers!