Note that this method only prepares the response for file sending. The file is not sent
until Response::send is called explicitly or implicitly. The latter is done after you return from a controller action.
The following is an example implementation of a controller action that allows requesting files from a directory
that is not accessible from web:
php
public function actionFile($filename)
{
$storagePath = Yii::getAlias('@app/files');
check filename for allowed chars (do not allow ../ to avoid security issue: downloading arbitrary files)
if (!preg_match('/^[a-z0-9]+\.[a-z0-9]+$/i', $filename) || !is_file("$storagePath/$filename")) {
throw new \yii\web\NotFoundHttpException('The file does not exists.');
}
return Yii::$app->response->sendFile("$storagePath/$filename", $filename);
}
public sendFile ( string $filePath, string $attachmentName = null, array $options = [] ) | ||
$filePath | string | the path of the file to be sent. |
$attachmentName | string | the file name shown to the user. If null, it will be determined from `$filePath`. |
$options | array | additional options for sending the file. The following options are supported: - `mimeType`: the MIME type of the content. If not set, it will be guessed based on `$filePath` - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up. |