I implemented a show action to retrieve a pdf file url
namespace :api do
namespace :v2 do
get '/patients/:id', to: 'patients#show'
end
end
http://localhost:3005/api/v2/patients/1894
{
"id": 1894,
"name": "Test",
"file": {
"url": "https://some-url-com"
},
"student_id": 20998,
"created_at": "2019-07-02T13:27:10.975-04:00",
"updated_at": "2019-07-02T13:54:53.248-04:00",
....
....
}
If a user accesses the show link then it should just return pdf file. I am trying to open pdf from the show endpoint. I tried following methods in controller but not having luck
patient = Patient.find(params[:id])
open(patient.file.url).read
also tried send_file
send_data patient.file.url, :type => "application/pdf", :disposition => 'attachment'
but not having luck. Is there any way I can have show url return pdf?
CodePudding user response:
First, get the file:
require 'open-uri'
download = open('https://some-url-com')
IO.copy_stream(download, 'tmp/my_document.pdf')
Then send the file as part of your JSON:
pdf_filename = File.join(Rails.root, 'tmp/my_document.pdf')
# add this to your JSON where desired
send_file(pdf_filename, :filename => 'your_document.pdf', :type => 'application/pdf')
CodePudding user response:
A simple way:
require "open-uri"
file = URI.open("https://some-url-com") # ruby 3 must use URI.open
# it's a File (or Tempfile), you can do file things to it
# file # => #<File:/tmp/open-uri20220818-414775-wdh4sb>
# file.path # => /tmp/open-uri20220818-414775-wdh4sb
# file.read # => "%PDF-1.5\n%\xE4\xF0\xED\xF8\n8 ..."
send_data file.read, type: "application/pdf"
# or
send_file file.path, type: "application/pdf"