我在Yii框架控制器中编写了以下代码。此代码在我的localhost上正常工作,但在服务器上无效。
有人可以告诉我代码的错误
以下是我在控制器中编写的代码
public function downloadFile($dir,$file,$extensions=[]){
if(is_dir($dir)){
$path = $dir.$file;
if(is_file($path)){
$fileinfo=pathinfo($path);
$extension=$fileinfo["extension"];
if(is_array($extensions)){
foreach($extensions as $e){
if($e===$extension){
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$file);
header('Content-Transfer-Encoding: binary');
readfile($path);
return true;
}
}
}
}else{
echo"error";
}
}
}
public function actionDownload(){
if(Yii::$app->request->get('file')){
$this->downloadFile("media/offer/",Html::encode($_GET["file"]),["jpg","png"]);
}
}
答案 0 :(得分:1)
你标记了yii2
,但它不是yii2,它是纯粹的PHP。
如何使用框架来做到这一点?
public function actionFile($filename)
{
$storagePath = Yii::getAlias('@app/files');
// check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
throw new \yii\web\NotFoundHttpException('The file does not exists.');
}
return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}
^将storagePath更改为您的文件目录。
就是这样,没有更多事情要做。
答案 1 :(得分:0)
用你的替换此功能,
public function downloadFile($dir,$file,$extensions=[]){
if(is_dir($dir)){
$path = $dir.$file;
if(is_file($path)){
$fileinfo=pathinfo($path);
$extension=$fileinfo["extension"];
if(is_array($extensions) && in_array($extension, $extensions)){
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
ob_clean();
flush();
readfile($path);
exit;
}
}else{
echo"error";
}
}
}
我刚跟这个叫
downloadFile("/var/www/html/", "test.php", ['php']);
它对我有用。