Serving Query Results for Download
Problem
You want to send database information to a browser for downloading rather than for display.
Solution
Unfortunately, there’s no good way to force a
download. A browser will process information sent to it according to
the Content-Type: header value, and if it has a
handler for that value, it will treat the information accordingly.
However, you may be able to trick the browser by using a
“generic” content type for which
it’s unlikely to have a handler.
Discussion
Earlier sections of this chapter discuss how to incorporate the
results of database queries into web pages, to display them as
paragraphs, lists, tables, or images. But what if you want to produce
a query result that the user can download to a file instead?
It’s not difficult to generate the response itself:
send a Content-Type: header preceding the
information, such as text/plain for plain text,
image/jpeg for a JPEG image, or
application/pdf or
application/msexcel for a PDF or Excel document. Then send a blank line and the content of the query result. The problem is that there’s no way to force the browser to download the information. If it knows what to do with the response based on the content type, it will try to handle the information as it sees fit. If it knows how to display text or images, it will. If it thinks it’s supposed to give a PDF or Excel document to a PDF viewer or to Excel, it will. Most browsers allow the user to select a download explicitly (for example, by right-clicking ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access