我有一个下载文件的脚本:
public function getResponse($file)
{
$response = new Response();
$ext = pathinfo($file, PATHINFO_EXTENSION);
var_dump($ext);
//$file .= '.pdf';
if (file_exists($file)) {
$fp = fopen($file, "rb");
$str = stream_get_contents($fp);
fclose($fp);
$response->headers->set('Content-Description','File Transfer');
$response->headers->set('Content-Type','application/octet-stream');
$response->headers->set('Content-Disposition','attachment; filename='.basename($file));
$response->headers->set('Content-Transfer-Encoding','binary');
$response->headers->set('Expires','0');
$response->headers->set('Cache-Control','must-revalidate');
$response->headers->set('Pragma','public');
$response->headers->set('Content-Length',filesize($file));
$response->setContent($str);
}
return $response;
}
但是我有问题,我的var $文件没有扩展名,如果我添加扩展名,代码就可以了。 有没有办法下载猜测扩展名的文件?
感谢。
答案 0 :(得分:1)
查看glob()
功能。
这将允许您按模式搜索文件。如下所示:
$found = glob($file . ".*");
意识到你可能有多个匹配,你需要查看返回的数组。
if(count($found) == 1) {
// One file found. Life is good.
$filename = $found[0];
} else if(count($found) > 1) {
// Multiple files matched! Which one should we download? Zip them all up?
} else {
// No files found
}