Download File in Yii

2019-08-30 00:09发布

I am trying to write a script in Yii for downloading files from the server.

The files are located in webroot of the Yii project,

but I got every time file not exist error, could anyone see where is wrong:

public function actionDownload($id) {
    $audio = Audio::model()->findByPk($id);
    $file =  Yii::getPathOfAlias('webroot') . $audio->path;
    if (file_exists($file)) {
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename=' . $audio->path);
        header('Content-Length: ' . filesize($audio->path));
        $audio->downloaded = $audio->downloaded + 1;
        $audio->save();
    }else{
        echo "file not exist: ".$file;            
    }
    exit;
}

error I got is:

file not exist: /var/www/vhosts/ikhwanbiz.org/httpdocs/userfiles/reklames/media/deneme/sen%20dep%20olmisem.mp3

Thanks

Regards

Bili

标签: php yii
3条回答
贼婆χ
2楼-- · 2019-08-30 00:45

This is more of a php question than a yii one.

for eg,

<?php
header("Content-disposition: attachment; filename=huge_document.pdf");
header("Content-type: application/pdf");
readfile("huge_document.pdf");
?>

source: http://webdesign.about.com/od/php/ht/force_download.htm

查看更多
该账号已被封号
3楼-- · 2019-08-30 00:51

Bili, this works well for me and seem to be fine on most browsers.

$filename = 'your_file_name.csv';
header('Content-Disposition: attachment; charset=UTF-8; filename="'.$filename.'"');
$utf8_content = mb_convert_encoding($content, "SJIS", "UTF-8");
echo $utf8_content;
Yii::app()->end();
return;

Hope it helps, good luck!

查看更多
淡お忘
4楼-- · 2019-08-30 00:56

It looks like the filename portion $audio->path is URL-encoded, while the name of the actual file on the server is not. You should fix it at the source (no idea where that path is set from), but in the meantime an easy workaround would be to write

$file =  Yii::getPathOfAlias('webroot') . urldecode($audio->path);
查看更多
登录 后发表回答