Search code examples
phphtml2canvas

javascript - Default filename when saving from html2canvas or save as dialogue?


A friend of mine configured h2ml2canvas for me as I don't understand javascript. When saving using h2ml2canvas it generates a random filename e.g.

df0e604b2962492165eb8f2b31578171

Is there a way to specify a filename prefix? e.g. soccer then generate a random 3-4 digit number? Alternatively is there a way to open a save as dialogue instead of downloading an image on click? My download.php file.

<?php
$file = trim($_GET['path']);

// force user to download the image
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: image/png');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    unlink($file);
    exit;
}
else {
    echo "error not found";
}

?>

Solution

  • The filename in your case is actually generated (or not) by the PHP server-side, not the JavaScript you've quoted. When it returns the data to send back, it's including a Content-Disposition header, probably one that looks like this:

    Content-Disposition: attachment
    

    It's possible to suggest a filename to the browser by adding to that header:

    Content-Disposition: attachment; filename=soccer123.xyz
    

    In the PHP somewhere, you should find:

    header("Content-Disposition", "attachment");
    

    or similar. You can change it to:

    header("Content-Disposition", "attachment; filename=soccer-" . rand(100,999) . ".xyz");
    

    (Probably best to make the .xyz an appropriate extension for the type of image, e.g. .png or .jpg...)


    Re your edit, you can replace:

    header('Content-Disposition: attachment; filename='.basename($file));
    

    with

    header('Content-Disposition: attachment; filename=soccer-'.rand(100,999).'.xyz');
    

    again you'll want a correct extension instead of .xyz.