【问题标题】:Magento2 need to create the download link in custom moduleMagento2 需要在自定义模块中创建下载链接
【发布时间】:2016-10-03 06:28:47
【问题描述】:

我在 Magento2 中创建了简单的自定义模块。现在正确显示页面我需要在该页面上创建链接,该链接下载模块 web 文件夹中的 PDF 文件。

对于 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>

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

请让我知道我需要在哪里编写链接的下载代码

谢谢。

【问题讨论】:

标签: magento magento2


【解决方案1】:

变体 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'); ?>

【讨论】:

    【解决方案2】:

    这对我有用

     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'
          );
      }
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多