tutulang
tutulang

Reputation: 31

Yii2 sendfile response

I am new to Yii2 and I would really appreciated if anyone could help me to solve the problem. I want to make a download link and I use

Yii::$app->response->sendFile($path, $name, ['inline' => false])->send();

in download function but it just read the content of the file and display straight in the page. What I want to do is when users click the download link, the download dialog will pop up or the file will be automatically downloaded, rather than display the content. Can anyone please help me?

Upvotes: 3

Views: 13918

Answers (4)

user13773825
user13773825

Reputation: 1

$mimetype='zip'; $mimetype='csv';
Yii::$app->response->sendFile($path.$name, $name, ['mimeType'=>$mimetype, 'inline'=>false]);    
return true;

Upvotes: -2

Red Bottle
Red Bottle

Reputation: 3090

Instead of :

 sendFile();

Try :

xSendFile()

Upvotes: -1

What you can do is use php header function:

public function actionDownload() {
    $file = $_GET["file"];
    $name = str_replace('files/prices/', '', $file);

    header("Content-Disposition: attachment; filename=\"" . urlencode($name) . "\"");
    header("Content-Type: application/pdf");
    header("Content-Description: File Transfer");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . filesize($file));

    ob_clean();
    flush();

    readfile($file);
}

And then call the link like this, with a timestamp: http://page.com/download?file=files/prices/sillas.pdf&ts=1490725032

Upvotes: -1

Marcin
Marcin

Reputation: 51

I had exactly the same problem. It turned out that my link to download action was placed inside the Pjax::begin() Pjax::end() methods, so the content of the file was treated as update for the page.

My solution: add data-pjax="0" attribute to download link.

Upvotes: 5

Related Questions