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

时间:2015-09-14 16:07:34

标签: pdf silverstripe

I have some code I'm working on for a PDF download page type in SilverStripe that allows people to upload a PDF file to the backend. In turn, this PDF file is then read into the top navigation as a link that, when clicked, automatically downloads the PDF file.

I have most of the code set up:

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

}

But the one thing I'm stuck on at the moment is how to get the url of the PDF file into the readfile() command. $obj right now is being set to get the id of the specific PDF file for the page....so do I need do use something like $obj.URL or $obj.Link in readfile()?

1 个答案:

答案 0 :(得分:1)

您目前正在请求PDFTemplate对象,而不是File对象,这样才会出现问题 - 但您不应该将ID传递给此页面下载它无论如何因为页面已经有了这些信息。

如果您不需要隐藏相关PDF的直接网址,那么这样的内容可能会轻松得多并提供更好的效果:

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