I am using the Yii framework and i have the website to allow the admin to upload a text file or a pdf.Now I want to allow the user to click on a link and start downloading that file.How is this achieved inside the Yii framework?
I am storing the files at Yiiapplication/uploads/downloads/test.txt.
I have tried the following code that i have found online but it is not working.
Yii::app()->request->sendFile(Yii::getPathOfAlias('webroot').'/uploads/downloads/23602414.txt','click me');
Do i need to improve on it all it is downloading is a text file with '<a href=
' which is not the original content of the file.
Uploading files in Yii is usually done with the help of yii\web\UploadedFile which encapsulates each uploaded file as an UploadedFile object. Combined with yii\widgets\ActiveForm and models , you can easily implement a secure file uploading mechanism.
This extension provides file storage abstraction layer for Yii2. This abstraction introduces 2 main terms: 'storage' and 'bucket'. 'Storage' - is a unit, which is able to store files using some particular approach. 'Bucket' - is a logical part of the storage, which has own specific attributes and serves some logical mean.
Yii is an open source project released under the terms of the BSD License . This means that you can use Yii for free to develop either open-source or proprietary Web applications.
The Definitive Guide to Yii 2.0 and the API Documentation are available for offline browsing. Below you will find the download packages including the HTML files of Guide and API Documentation as well as links to the PDF versions of the Guide in different languages. Yii 1.1 is currently in maintenance mode.
if you prefer not using extension , why not try to create a simple method to force download.
public function downloadFile($fullpath){
if(!empty($fullpath)){
header("Content-type:application/pdf"); //for pdf file
//header('Content-Type:text/plain; charset=ISO-8859-15');
//if you want to read text file using text/plain header
header('Content-Disposition: attachment; filename="'.basename($fullpath).'"');
header('Content-Length: ' . filesize($fullpath));
readfile($fullpath);
Yii::app()->end();
}
}
public function actionDownload(){
$path = Yii::getPathOfAlias('webroot')."/uploads/downloads/23602414.pdf";
$this->downloadFile($path);
}
and make link to download those file
<?php echo CHtml::link('Download file',array('youController/download')); ?>
you can improve this code by making content type more flexible by checked file type before decide header type.could be pdf|txt|jpeg|etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With