【问题标题】:Auto-rename downloaded file based on page title?根据页面标题自动重命名下载的文件?
【发布时间】:2013-06-19 20:04:12
【问题描述】:

基本上,我希望在每个页面的底部都有一个下载 .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 javascript jquery html perl


    【解决方案1】:

    force a download with PHP时,可以在Content-Disposition标头中使用filename=动态设置下载文件名。

    download_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>
    

    【讨论】:

    • 好的,我刚刚测试了它,它非常接近我想要的。但是,当下载文件时,它被命名为“dynamicfilename.zip”。我需要改变什么来解决这个问题?
    • @user1135462 我在答案的底部提到了这一点。您需要在下载链接中包含页面标题。我已经稍微更新了我的答案以使这一点更清楚。
    • 我尝试像http://yoursite.com/download/zip.php?title=The+Page+You+Were+Just+On 一样链接到它,看看它是否会下载The+Page+You+Were+Just+On.zip,但名称仍然是dynamicfilename.zip
    • @user1135462 查看我的答案的编辑。您需要上传下载脚本的代码以将文件名设置为$_GET['title']
    • 您需要规范化 $download_file_name 值并使其文件路径安全,然后再将其用作空格,并且其他一些字符会破坏标题。 +1 很好的答案
    【解决方案2】:

    我认为这是新属性的情况 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

    【讨论】:

    猜你喜欢
    • 2016-07-03
    • 2011-03-06
    • 2020-02-13
    • 1970-01-01
    • 2018-02-26
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多