根据页面标题自动重命名下载的文件


Auto-rename downloaded file based on page title?

基本上,我希望在每个页面的底部都有一个下载.zip文件的链接。在这个.zip文件里,我会有一个PDF文件。

任何时候下载.zip文件时,我都希望它的标题与页面的标题相同——此外,我希望PDF也相同。

例如,如果他们是从标题为"This Is My page"的页面下载的,那么.zip文件应该是"This Is My page.zip",里面的PDF应该是"This Is My page.PDF"。无论从哪个页面下载,PDF都将具有完全相同的内容。

我对任何解决方案都持开放态度,无论是PHP、Javascript、HTML等。

使用PHP强制下载时,可以在Content-Disposition标头中使用filename=来动态设置下载的文件名。

下载_zip.php

$actual_file_name = '/var/yourserver/file.zip';
$download_file_name = substr(str_replace(array('''/|>< ?%'"*'), '_', $_GET['title'] . '.zip'), 0, 255);
$mime = 'application/zip';
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename="'. $download_file_name .'"'); // Set it here!
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($actual_file_name));
header('Connection: close');
readfile($actual_file_name);
exit();

要获得最后一个页面的页面标题,最简单的方法可能是在下载链接中将标题作为$_GET变量传递。从带有下载链接的页面:

<a href="http://yoursite.com/download_zip.php?title=The+Page+You+Were+Just+On">Download Zip File With This Page's Title</a>

这将要求您在链接中包含页面标题,因此为了避免在两个位置更新页面标题,请尝试使用$page_title变量。在带有下载链接的页面中:

<?php
$page_title = 'Page Title';
?>
<html>
<head>
    <title><?= $page_title ?></title>
</head>
<body>
    <a href="http://yoursite.com/download_zip.php?title=<?= urlencode($page_title) ?>">Download Zip File With This Page's Title</a>
</body>
</html>

我认为这是新属性的一个例子HTML5 中引入的下载

<a id="link" href="path/to/file.zip" >Download</a>
<script>
    $(document).ready( function(){
            var sPath=window.location.pathname;
            var sPage = sPath.substring(sPath.lastIndexOf('/') +1, sPath.lastIndexOf('.'));
            $('#link').attr("download",sPage +".zip");
    });
</script>

阅读此处:http://davidwalsh.name/download-attribute

支持的浏览器:http://caniuse.com/#feat=download