file_get_contents是一個壞主意。通過file_get_contents讀取大量圖像會殺死我的小服務器。我不得不尋找另一種解決方案,這對我來說現在完美並且非常快速。
關鍵是使用readfile($ sFileName)而不是file_get_contents。 Symfony Stream Response可以接收一個回調函數,它將在發送($ oResponse-> send())時執行。所以這是一個使用readfile()的好地方。
作爲一個小好處,我寫下了一種緩存方式。
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class ImageController
{
public function indexAction(Request $oRequest, Response $oResponse)
{
// Get the filename from the request
// e.g. $oRequest->get("imagename")
$sFileName = "/images_directory/demoimage.jpg";
if(! is_file($sFileName)){
$oResponse->setStatusCode(404);
return $oResponse;
}
// Caching...
$sLastModified = filemtime($sFileName);
$sEtag = md5_file($sFileName);
$sFileSize = filesize($sFileName);
$aInfo = getimagesize($sFileName);
if(in_array($sEtag, $oRequest->getETags()) || $oRequest->headers->get('If-Modified-Since') === gmdate("D, d M Y H:i:s", $sLastModified)." GMT"){
$oResponse->headers->set("Content-Type", $aInfo['mime']);
$oResponse->headers->set("Last-Modified", gmdate("D, d M Y H:i:s", $sLastModified)." GMT");
$oResponse->setETag($sEtag);
$oResponse->setPublic();
$oResponse->setStatusCode(304);
return $oResponse;
}
$oStreamResponse = new StreamedResponse();
$oStreamResponse->headers->set("Content-Type", $aInfo['mime']);
$oStreamResponse->headers->set("Content-Length", $sFileSize);
$oStreamResponse->headers->set("ETag", $sEtag);
$oStreamResponse->headers->set("Last-Modified", gmdate("D, d M Y H:i:s", $sLastModified)." GMT");
$oStreamResponse->setCallback(function() use ($sFileName) {
readfile($sFileName);
});
return $oStreamResponse;
}
}
剛剛看到的消息,但是這將有助於。 [用symfony下載文件](http://www.inanzzz.com/index.php/post/cko4/downloading-a-file-with-symfony) – BentCoder