Xiabili
Xiabili

Reputation: 486

Download File in Yii

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

Upvotes: 0

Views: 9634

Answers (3)

Gideon Rosenthal
Gideon Rosenthal

Reputation: 2033

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

Upvotes: 0

Jon
Jon

Reputation: 437904

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);

Upvotes: 0

nights
nights

Reputation: 419

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!

Upvotes: 3

Related Questions