For some strange reason I need to save a file (normally downloaded directly) in the server. In my case I have a PDF file created with PDFKit that I need to keep.
# app/controllers/reports_controller.rb
def show
@report = Report.find(params[:id])
respond_to do |format|
format.pdf { render :text => PDFKit.new(report_url(@report)).to_pdf }开发者_JAVA百科
end
end
If I go to reports/1.pdf I get the report I am expecting but I want to keep it in the server.
Is there a Raily way to save a file in the server from a respond to?
Just a quick note before I get to the actual answer: It looks like you're passing a fully-qualified URL (report_url(@report)
) to PDFKit.new
, which is a waste--it means PDFKit has to make a request to the web server, which in turn needs to go through Rails' router and so on down the line to fetch the contents of the page. Instead you should just render the page inside your controller with render_to_string
and pass it to PDFKit.new
, since it will accept an HTML string. Keeping that in mind...
This is covered in the "Usage" section of PDFKit's README. You would do something like this:
def show
@report = Report.find(params[:id])
kit = PDFKit.new render_to_string(@report) # pass any options that the
pdf_file = kit.to_file '/some/file/path.pdf' # renderer needs here (same
# options as `render`).
# and if you still want to send it to the browser...
respond_to do |format|
format.pdf { render :file => pdf_file.path }
end
end
精彩评论