Niklas Riecken Niklas Riecken - 3 months ago 28
reST (reStructuredText) Question

SLIM API - Offer Files to Download

I am using Slim API for my Project. I want to offer Files for Download (Mostly PDF files). I found several Ways sending out a public link to the file, which i dont want. I also found an Middleware for the Version 2.4 of Slim, but I am using 3.x.

I just want to access the Route e.g. /downloads/version/2183
And the a Downlod with this certain File ID should start. I have a Path to the File on the Server in a variable available.

The Basic Idea behind is different restrictions, which user can download the file - but i can do that myself - the problem where I am stuck is, how to bring the Download over the Route to the Clients Browser

Does anyone know how to achieve this?

Cheers,
Niklas

Answer

This is actually very easy.

  1. Set the Proper Headers for the file on the Response Object
  2. Read the contents of the file into the body of the Response Object

$app->get('/my/file', function ($req, $res, $args) {
   return $res->withHeader('Content-Type', 'application/octet-stream')
               ->withHeader('Content-Disposition', 'attachment')
               ->write(file_get_contents("file.txt"));
});
Comments