-
Notifications
You must be signed in to change notification settings - Fork 34
/
FileController.php
72 lines (66 loc) · 1.74 KB
/
FileController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
namespace mdm\upload;
use Yii;
use yii\web\NotFoundHttpException;
/**
* Use to show or download uploaded file. Add configuration to your application
*
* ~~~
* 'controllerMap' => [
* 'file' => 'mdm\upload\FileController',
* ],
* ~~~
*
* Then you can show your file in url `Url::to(['/file','id'=>$file_id])`,
* and download file in url `Url::to(['/file/download','id'=>$file_id])`
*
* @author Misbahul D Munir <[email protected]>
* @since 1.0
*/
class FileController extends \yii\web\Controller
{
public $defaultAction = 'show';
/**
* Show file
* @param integer $id
*/
public function actionShow($id)
{
$model = $this->findModel($id);
$response = Yii::$app->getResponse();
return $response->sendFile($model->filename, $model->name, [
'mimeType' => $model->type,
'fileSize' => $model->size,
'inline' => true
]);
}
/**
* Download file
* @param integer $id
* @param mixed $inline
*/
public function actionDownload($id, $inline = false)
{
$model = $this->findModel($id);
$response = Yii::$app->getResponse();
return $response->sendFile($model->filename, $model->name, [
'mimeType' => $model->type,
'fileSize' => $model->size,
'inline' => $inline
]);
}
/**
* Get model
* @param integer $id
* @return FileModel
* @throws NotFoundHttpException
*/
protected function findModel($id)
{
if (($model = FileModel::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}