在SilverStripe导航中设置link自动下载一个PDF文件

Set up link in SilverStripe navigation to automatically download a PDF file

我正在为 SilverStripe 中的 PDF 下载页面类型编写一些代码,允许人们将 PDF 文件上传到后端。反过来,此 PDF 文件将作为 link 读入顶部导航,单击后会自动下载 PDF 文件。

我已经设置了大部分代码:

<?php
class PDFTemplate extends Page {

    public static $db = array(
    );

    public static $has_one = array(
        'PDFFile' => 'File'
    );

    public static $has_many = array(
    );

    public function Link() {
        return '/home/download?ID=' . $this->ID;
    }

    public function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->addFieldToTab("Root.Main", new UploadField('PDFFile', "PDF File"), "Content");

        return $fields;
    }

}
class PDFTemplate_Controller extends Page_Controller {

    public static $allowed_actions = array (
        'download'
    );

    public function init() {
        parent::init();
    }

    public function download() {
        $id = $_GET['ID'];

        $obj = DataObject::get_by_id('PDFTemplate', $id);

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment;');
        header('Pragma: no-cache');

        return readfile("");
    }

}

但是我现在坚持的一件事是如何将 PDF 文件的 url 放入 readfile() 命令中。 $obj 现在被设置为获取页面的特定 PDF 文件的 ID...所以我需要在 readfile() 中使用 $obj.URL 或 $obj.Link 之类的东西吗?

您现在请求的是 PDFTemplate 对象,而不是 File 对象,所以这是个问题 - 但无论如何您都不需要将 ID 传递到此页面来下载它因为主页已经有该信息。

如果您不需要隐藏有问题的 PDF 的直接 URL,这样的事情可能会容易得多并且提供更好的性能:

  1. 删除 download() 和 Link() 函数。
  2. 在菜单的 .ss 模板中执行:<a <% if $PDFFile %>href="$PDFFile.Link" target="_blank"<% else %>href="$Link"<% end_if %>>