简体   繁体   中英

How to download and open a file form S3 via rails

I have controller for save, open, download files (such as: pdf, docx etc). I save them on S3. But I do not know, how can I download or open file. My controller

class PdfsController < ApplicationController
  before_action :set_pdf, only: %i[show edit update destroy download]
  before_action :set_url_file, only: %i[download show]

 def show
 send_file(@pdf_filename, filename: @pdf.path.to_s,
                          type: 'application/pdf',
                          x_sendfile: true,
                          disposition: 'inline')

 end

 def download
  send_file(@pdf_filename, filename: @pdf.path.to_s,
                          type: 'application/pdf',
                          x_sendfile: true)

 end

 private

 def set_url_file
  if Rails.env.production?
    @pdf_filename = File.join(@pdf.path.to_s)
  else
    @pdf_filename = File.join(Rails.root, "public#{@pdf.path}")
  end
 end
end

action show display pdf file in browser (only pdf), action download save whatever file locally.

It worked when I saved files locally. But if I deploy project on heroku, I obtain an error ActionController::MissingFile . After I learned that I can download file I must use aws-sdk . But i do not understand how it is used for opening and downloading. How can I do that?

when you are on Rails 5.2 or higher you don't need the aws-sdk . Just use Active Storage for that: https://guides.rubyonrails.org/v5.2/active_storage_overview.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM