Answers:
您可以通过扩展\Magento\Backend\App\Action
后端或\Magento\Framework\App\Action\Action
前端来创建控制器动作。
并使其如下所示:
<?php
namespace Your\Namespace\Here;
class ClassName extends \Magento\Backend\App\Action
{
public function __construct(
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Backend\App\Action\Context $context
) {
$this->resultRawFactory = $resultRawFactory;
$this->fileFactory = $fileFactory;
parent::__construct($context);
}
public function execute()
{
//do your custom stuff here
$fileName = 'file name for download here';
$this->fileFactory->create(
$fileName,
null, //content here. it can be null and set later
base dir of the file to download here
'application/octet-stream', //content type here
content lenght here...can be null
);
$resultRaw = $this->resultRawFactory->create();
$resultRaw->setContents(contents of file here); //set content for download file here
return $resultRaw;
}
}
$this->fileFactory->create()
因为这已经是响应实现,无需执行$resultRaw
也可以提供您要下载的文件的路径:
//Send file for download
//@see Magento\Framework\App\Response\Http\FileFactory::create()
return $this->_fileFactory->create(
//File name you would like to download it by
$filename,
[
'type' => "filename", //type has to be "filename"
'value' => "folder/{$filename}", // path will append to the
// base dir
'rm' => true, // add this only if you would like the file to be
// deleted after being downloaded from server
],
\Magento\Framework\App\Filesystem\DirectoryList::MEDIA
);
根据马吕斯给出的答案。
class Download extends \Magento\Framework\App\Action\Action
{
protected $resultRawFactory;
protected $fileFactory;
public function __construct(
\Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
\Magento\Backend\App\Action\Context $context
) {
$this->resultRawFactory = $resultRawFactory;
$this->fileFactory = $fileFactory;
parent::__construct($context);
}
public function execute()
{
try{
$fileName = 'FileName'; // the name of the downloaded resource
$this->fileFactory->create(
$fileName,
[
'type' => 'filename',
'value' => 'relative/path/to/file/from/basedir'
],
DirectoryList::MEDIA , //basedir
'application/octet-stream',
'' // content length will be dynamically calculated
);
}catch (\Exception $exception){
// Add your own failure logic here
var_dump($exception->getMessage());
exit;
}
$resultRaw = $this->resultRawFactory->create();
return $resultRaw;
}
}
没有正确的权限(即使这里需要读取,Magento也会检查是否具有写权限)将导致奇怪的错误。“该网站已关闭或移动”或类似的内容。
值得在$ fileFactory-> create()内部的逻辑上稍作尝试。