web\Response sendFile()

sendFile() public method

Sends a file to the browser.

Note that this method only prepares the response for file sending. The file is not sent until 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:

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);
}

See also:

public $this sendFile ( $filePath, $attachmentName = null, $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.
return $this

The response object itself

doc_Yii
2016-10-30 17:16:24
Comments
Leave a Comment

Please login to continue.