# Slim 3 Download Files

**URL:** <https://discourse.slimframework.com/t/slim-3-download-files/224>\
**Category:** Questions\
**Created:** [May 9, 2016, 1:28pm UTC](https://discourse.slimframework.com/t/slim-3-download-files/224 "2016-05-09T13:28:50Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![llvdl](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.slimframework.com/llvdl/32/78_2.png) [@llvdl](https://discourse.slimframework.com/u/llvdl)\
**Post date:** [May 9, 2016, 7:08pm UTC](https://discourse.slimframework.com/t/slim-3-download-files/224/2 "2016-05-09T19:08:20Z")

</div>

The data needs to written to the body of the response object. You can use the built-in Slim `Stream` class together with `fopen` to to this for you:

```
    $app->get('/test-download', function($request, Slim\Http\Response $response, $args) {
        $file = __DIR__. '/test.html';
        $fh = fopen($file, 'rb');

        $stream = new \Slim\Http\Stream($fh); // create a stream instance for the response body

        return $response->withHeader('Content-Type', 'application/force-download')
                        ->withHeader('Content-Type', 'application/octet-stream')
                        ->withHeader('Content-Type', 'application/download')
                        ->withHeader('Content-Description', 'File Transfer')
                        ->withHeader('Content-Transfer-Encoding', 'binary')
                        ->withHeader('Content-Disposition', 'attachment; filename="' . basename($file) . '"')
                        ->withHeader('Expires', '0')
                        ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
                        ->withHeader('Pragma', 'public')
                        ->withBody($stream); // all stream contents will be sent to the response
    });

```

The `Content-Length` header will be automatically appended.

The code also worked for me with one `Content-Type` header, and without the `Content-Transfer-Encoding` header. So you may be able to simplify this by leaving headers out.

---

_[View the full topic](https://discourse.slimframework.com/t/slim-3-download-files/224)._
