Alex Reynolds
Alex Reynolds

Reputation: 96966

How to trigger the browser to save file via CGI?

I have the following hidden form:

<form id='export_svg_container_single_form'
      action='exportSVG.pl'
      method='post'
      target='_blank'
      style='display:none;'>
  <input type='text'
         id='export_svg_container_single_form_data'
         name='export_svg_data'
         style=';' />
</form>

The export_svg_data field value gets populated with an SVG document before form submission.

When submitted, this acts on the following simple CGI script, written in Perl:

#!/usr/bin/perl

use strict;
use warnings;
use CGI;
use CGI::Pretty qw/:standard/;

my $val = param('export_svg_data');
print "Content-Type:image/svg+xml\n";
print "Content-Disposition: inline\n";
print "Content-Description: File to download\n\n";
print $val;

When submitted, the hidden form also opens a new tab and displays (in this case) an SVG document. The end user can then save the window to a file.

Instead, on submitting the form, what I would like to do is have the browser automatically open a Save or Save As dialog box so that the user can pick a filename and save the document, instead of rendering the SVG within the browser window.

How might I do this with JavaScript or the appropriate changes to the CGI script? (I'd like to leave the parent form page untouched, i.e. open a new tab or window, if that is required.) Thanks for your advice.

To clarify again, I am looking for a solution which brings up the Save dialog box. I do not want the script to determine the filename and to save it somewhere random, without any user intervention.

Upvotes: 0

Views: 2864

Answers (2)

alexsergeyev
alexsergeyev

Reputation: 535

BTW... Can you clarify what is this for? Could be alternative solutions...

Content-Disposition is not going to help universally, what you eventually need is to serve this file from virtual URL, say

/generated-images/generatedname.svg

then you say in your HTML

<form ... action="/generated-images/generatedname.svg" ...>

and your script similar to these Apache directives (in config or .htaccess), I'm not guaranteeing this to work but I think it's close to truth (you'll also need proper paths and settings to run that CGI by Apache)

<Directory /.../generated-images/>
    Action mirror-svg-data /path/somescript.cgi
    AddHandler mirror-svg-data .svg
</Directory>

Or you can also rewrite your URLs to script but I'm not sure how internal redirect would work with POST, you may experiment with this:

RewriteRule /generated-images/.*\.svg /somepath/script.cgi [L]

Good luck!

Upvotes: -1

Quentin
Quentin

Reputation: 943996

Use Content-Disposition: attachment; filename="example.svg" instead.

Upvotes: 5

Related Questions