Here's how to currently send a file with Yii3 in the most efficient way. We need to think about where to put such code not to write it every time.
<?php
declare(strict_types=1);
namespace App\Controller;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Yiisoft\Http\ContentDispositionHeader;
use Yiisoft\Http\Header;
final class SiteController
{
public function __construct(
private ResponseFactoryInterface $responseFactory
)
{
}
private function sendFile(
string $filePath,
?string $attachmentName,
?string $disposition,
?string $mimeType,
?string $xHeader
): ResponseInterface
{
if ($attachmentName === null) {
$attachmentName = basename($filePath);
}
if ($mimeType === null) {
$info = new \finfo(FILEINFO_MIME_TYPE);
$mimeType = @$info->file($filePath) ?: null;
if ($mimeType === null) {
$mimeType = 'application/octet-stream';
}
}
$dispositionHeader = ContentDispositionHeader::value(
$disposition ?? ContentDispositionHeader::ATTACHMENT,
$attachmentName
);
return $this->responseFactory
->createResponse()
->withHeader($xHeader ?? 'X-Sendfile', $filePath)
->withHeader(ContentDispositionHeader::name(), $dispositionHeader)
->withHeader(Header::CONTENT_TYPE, $mimeType);
}
public function test(): ResponseInterface
{
return $this->sendFile('~/test.jpg');
}
}
https://github.com/yiisoft/response-download