Magento2 需要在自定义模块中创建下载 link

Magento2 need to create the download link in custom module

我已经在 Magento2 中创建了简单的自定义模块。现在正确显示页面我需要在该页面上创建 link 以下载模块 Web 文件夹中的 PDF 文件。

For Ex app\code\Magento\Hello\view\frontend\web\pdf\test.pdf

我该怎么办?我是否需要为新功能添加路由,如果是,我该怎么做,目前我的路由文件是

\app\code\Magento\Hello\etc\frontend\routes.xml

<?xml version="1.0"?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="hello" frontName="hello">
            <module name="Magento_Hello"/>
        </route>
    </router> 
</config>

其余文件是没有修改的简单模块文件。

请让我知道我需要在哪里编写 link

的下载代码

谢谢。

变体 1

如何将您的 test.pdf 移动到 pub/media 目录并像这样链接:

<a href="/pub/media/test.pdf">here</a>

但是pub/media目录应该是动态收集的,另请参考:https://mage2.pro/t/topic/153

变体 2

如果您想将资产保存在模块文件夹中,例如在 view/frontend/web/Test.pdf 中,您可以像这样在 phtml 模板中寻址 Web 目录:

<?php echo $block->getViewFileUrl('Vendor_Modulename/Test.pdf'); ?>

这对我有用

 namespace Namespace\ModuleName\Controller\ControllerName;

 use Magento\Framework\App\Filesystem\DirectoryList;
 class Download extends \Magento\Framework\App\Action\Action
 {
    protected $directory_list;
    protected $fileFactory;
    public function __construct(
    \Magento\Framework\App\Action\Context $context, 
    DirectoryList $directory_list,
    \Magento\Framework\App\Response\Http\FileFactory $fileFactory) {
    $this->directory_list = $directory_list;
    $this->fileFactory = $fileFactory;
    parent::__construct($context);
 }

public function execute()
{
  $file = $this->getRequest()->getParam('file');

  if(isset($file) && !empty($file)) {

    $pdf = \Zend_Pdf::load($this->directory_list->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . $file);
    $fileName = test.pdf;
    $this->fileFactory->create(
    $fileName,
    str_replace('/Annot /Subtype /Link', '/Annot /Subtype /Link /Border[0 0 0]', $pdf->render()),
    \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR,
    'application/pdf'
      );
  }
 }
}