javascript - 从html2canvas保存时的默认文件名或另存为对话框中的文件名是什么?

3

我的朋友为我配置了h2ml2canvas,因为我不懂JavaScript。使用h2ml2canvas保存时,它会生成一个随机文件名,例如

df0e604b2962492165eb8f2b31578171

有没有一种方法可以指定文件名前缀?例如,足球然后生成一个随机的3-4位数字?或者,有没有一种方法可以在单击时打开另存为对话框而不是下载图像?我的download.php文件。

<?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";
}

?>

在您的情况下,文件名实际上是由PHP服务器端生成(或未生成),而不是您引用的JavaScript。 - T.J. Crowder
在这种情况下,是否有可能更改JS以打开“另存为”对话框? - MBM
@ MBM:不是直接的,这就是为什么需要涉及到 PHP 的部分。 :-) - T.J. Crowder
1个回答

0

在您的情况下,文件名实际上是由 PHP 服务器端生成(或未生成),而不是您引用的 JavaScript。当它返回要发送的数据时,它会包含一个 Content-Disposition 头,可能看起来像这样:

Content-Disposition: attachment

可以通过在标题中添加以下内容向浏览器建议文件名:

Content-Disposition: attachment; filename=soccer123.xyz

在 PHP 中的某个地方,你应该找到:
header("Content-Disposition", "attachment");

或类似的。您可以将其更改为:

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

(最好将.xyz更改为适合图像类型的扩展名,例如.png.jpg...)


关于您的编辑,您可以替换为:

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

使用

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

再次提醒您,需要使用正确的扩展名,而不是.xyz


我已经包含了从我的 download.php 脚本中的代码。文件名链接到变量,因此我不确定需要做哪些更改。 - MBM
太棒了!谢谢。 - MBM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接