yii\web\Response::sendContentAsFile PHP Method

sendContentAsFile() public method

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.
See also: sendFile() for an example implementation.
public sendContentAsFile ( string $content, string $attachmentName, array $options = [] )
$content string the content to be sent. The existing [[content]] will be discarded.
$attachmentName string the file name shown to the user.
$options array additional options for sending the file. The following options are supported: - `mimeType`: the MIME type of the content. Defaults to 'application/octet-stream'. - `inline`: boolean, whether the browser should open the file within the browser window. Defaults to false, meaning a download dialog will pop up.
    public function sendContentAsFile($content, $attachmentName, $options = [])
    {
        $headers = $this->getHeaders();
        $contentLength = StringHelper::byteLength($content);
        $range = $this->getHttpRange($contentLength);
        if ($range === false) {
            $headers->set('Content-Range', "bytes */{$contentLength}");
            throw new RangeNotSatisfiableHttpException();
        }
        list($begin, $end) = $range;
        if ($begin != 0 || $end != $contentLength - 1) {
            $this->setStatusCode(206);
            $headers->set('Content-Range', "bytes {$begin}-{$end}/{$contentLength}");
            $this->content = StringHelper::byteSubstr($content, $begin, $end - $begin + 1);
        } else {
            $this->setStatusCode(200);
            $this->content = $content;
        }
        $mimeType = isset($options['mimeType']) ? $options['mimeType'] : 'application/octet-stream';
        $this->setDownloadHeaders($attachmentName, $mimeType, !empty($options['inline']), $end - $begin + 1);
        $this->format = self::FORMAT_RAW;
        return $this;
    }

Usage Example

Example #1
-1
 /**
  * https://github.com/yiisoft/yii2/issues/7529
  */
 public function testSendContentAsFile()
 {
     ob_start();
     $this->response->sendContentAsFile('test', 'test.txt')->send(['mimeType' => 'text/plain']);
     $content = ob_get_clean();
     static::assertEquals('test', $content);
     static::assertEquals(200, $this->response->statusCode);
     $headers = $this->response->headers;
     static::assertEquals('application/octet-stream', $headers->get('Content-Type'));
     static::assertEquals('attachment; filename="test.txt"', $headers->get('Content-Disposition'));
     static::assertEquals(4, $headers->get('Content-Length'));
 }