In your Yii2 controller it is quite common practice to return the stream of a file to the browser for your user to download.
However, it’s not so well documented you can set any stream reference as the content of your response.
In this scenario we want to have a file behind yii2 authentication that only some users can view. We could use the
1 | sendFile |
function to send a file stream to the browser. This will prompt the user to download the file. In this situation we just want the users to view the files.
This is where the
1 | stream |
property of the Yii2 response comes in. With this bit of code it will send the stream as the content of your response. The below code is a snippet will send a PNG file reference to the browser without using the
1 | file_get_contents |
function where we will be loading the full content of the file into memory rather than reading the file line by line.
1
2
3
4
5
6 public function actionViewFile(): void
{
Yii::$app->response->format = Yii::$app->response::FORMAT_RAW;
Yii::$app->response->headers->set('Content-Type', 'image/png');
Yii::$app->response->stream = fopen('/path/to/my.png', 'rb');
}
The stream property of the response can also be the stream from the
1 | flysystem |
fs adapter, so we can stream our files from s3 straight to the browser. Below is a snippet using yii2 flysystem to connect to an aws s3 bucket.
1
2
3
4
5
6 public function actionViewFile(): void
{
Yii::$app->response->format = Yii::$app->response::FORMAT_RAW;
Yii::$app->response->headers->set('Content-Type', 'image/png');
Yii::$app->response->stream = Yii::$app->fs->readStream('my.png');
}
More reads
Mkcert all the things
After Ade Attwood’s recent dive into TLS and creating server certificates with a root ca. This is a much simpler way with mkcert…
Future Web Design Skills
This post is a version of a recent lecture. The question is “What skills and knowledge might future designers be expected to know”.
Practically output – Our working summer 2020
It has been a busy summer for us here since March 2020. Here are just some of the design-led projects that we have completed in this time. Adapted from a show and tell presentation by Anna and Sam.