-->

How to Implement Resumable Download in Silex

2019-03-16 13:31发布

问题:

In silex I can do this to force-download a file:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

$app = new Silex\Application();

// Url can be http://pathtomysilexapp.com/download
$app->get('/download', function (Request $request) use ($app) {
    $file = '/path/to/download.zip';

    if( !file_exists($file) ){
        return new Response('File not found.', 404);
    }

    return $app->sendFile($file)->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, 'download.zip');
});

$app->run();

This works well for smaller files. However my use case requires downloading a big that can be paused/resumed by a download manager.

There is an example about file streaming but it doesn't seem to be what I am looking for. Has somebody done this before? I could just use the answer from here and be done with it. But it would be nice if there is a silexy way of doing this.

回答1:

Implementing it is quite trivial if you have a the file on the drive. It is like paginating records from a table.

Read the headers, open the file, seek to the desired position and read the the size requested.

You only need to know a little bit about the headers from the request & response.

Does the server accept ranges:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests

HTTP 206 status for content ranges:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206

Info about the content range headers:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Range



标签: symfony silex