4

I have a Python CGI script script.py running on a server. It produces a CSV file as output. I want computer-inexperienced people that don't know about file extensions to be able to just save the file to their hard drive and use it by double-clicking.

The problem: If they now click "OK" in the save dialog of the browser, the saved file's name is script.py, instead of script.csv.

How can I set some sort of "default filename" from within the CGI? Maybe some HTTP header trickery? I don't have access to the server configuration.

Turion
  • 5,684
  • 4
  • 26
  • 42

1 Answers1

5

You need to set a Content-Disposition header, with a filename attribute. See an earlier question for some discussion.

Yours would look like:

Content-Disposition: attachment; filename=script.csv

As well as setting the filename, this will tell the browser to save the file, rather than to open it inline.

Community
  • 1
  • 1
Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
  • Worked instantly, thank you very much. I think that it's still helpful to have my question around here because it might be easier to be searched for than the question mentioned by you. – Turion Sep 27 '11 at 09:50
  • Evidently - if the other question had been easy to find, you would have found it! – Tom Anderson Sep 27 '11 at 10:48
  • 1
    A short note to anyone who later reads this and wants what I want: for the file to display but when the user tries to save it, it uses the substitute filename. To do that, use the above but use `inline` instead of `attachment`. – jep Oct 16 '13 at 18:52