I've created an upload file page in Yii which successfully saves in both database and local folder and I've been researching on how to download this file and I've come across this and tried to follow it.
In my model, I added this to the rules:
array('location', 'file', 'types'=>'jpg,jpeg, png, doc,docx,xls,xlsx,pdf',
'maxSize'=>1024 * 1024 * 3, // 3MB
'tooLarge'=>'The file was larger than 3MB. Please upload a smaller file.',
'allowEmpty' => true),
);
My controller looks like this:
public function actionDisplaySavedImage()
{
$model=$this->loadModel($_GET['id']);
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename='.$model->location);
echo $model->location;
}
and my view:
<?php echo CHtml::link('Download Here',array('displaySavedImage','id'=>$model->primaryKey)); ?>
I could download the file, but when I open it, its a messed up file type.
Like for example if I download an image, the windows photo viewer would appear but it would display a text saying "file type not supported" or something like that.
Same is through if I try in different file types like .docx. Microsoft word would say that it is not supported.
Please help
public function actionDisplaySavedImage($id){
$model = $this->loadModel($id);
$upload_path = Yii::app()->params['uploadPath'] . $model->location; // /var/home/site/upload/image.jpg
if (file_exists($upload_path)) {
Yii::app()->getRequest()->sendFile($model->location, file_get_contents($upload_path));
} else {
$this->render('httperror404');
}
}
Below is the code that i use for csv file download from my local folder. try this Hope it works for you as well. You can chnage header as per your requirement.
$reportFileName = pathinfo($model->report_file);
$csvFileName = "your file name";
header('Content-Type: application/csv');
header('Content-Length: '.filesize($folder.$csvFileName.'.csv'));
header('Content-disposition: inline; filename='.$csvFileName.'.csv');
echo file_get_contents($folder.$csvFileName.'.csv');