Symfony 3.4 - Transfert API stream file to client download

874 Views Asked by At

An API sends me a stream containing a zip archive of several files that I choose by providing their ids in the parameter SelectedIds of my request. I receive a PSR7 response that I pass to HttpFoundationFactory to return a Response that corresponds to what the Symfony controller should return.

(the goal is to download the zip in the client side browser.)

Here is the content of my controller method

$client  = $this->getApiClient();
$user    = $this->getUser();
$idList  = [51,52,53];
$psr7ApiResponse = $client->post('/v1/get-zip', [
    'headers'     => [
        'Authorization' => sprintf('Bearer %s', $user->getToken()),
    ],
    'http_errors' => false,
    'json'        => [
        'SelectedIds' => $idList,
    ],
]);

$httpFoundationFactory = new HttpFoundationFactory();
return $httpFoundationFactory->createResponse($psr7ApiResponse);

It works perfectly locally but on the server I receive nothing, blank page. Would you know which way I should look because I have no error log, it looks like the stream is empty but I don't know how to check.

I tested the API with postman and it's ok ; my controller sends me back a 200 as well

1

There are 1 best solutions below

0
On

Follow those steps in order to debug the problem:

1. Check if the content of $psr7ApiResponse is valid and correct

You are in a different environment. Maybe for some reason your server side script does not receive a valid answer. Maybe the authentication does not work. Print debug the answer you receive to some log file as detailed as necessary (use loggers: https://symfony.com/doc/current/logging.html).

If the content or the resulting class of the call are not correct the problem is within the remote call communication and you have to debug that. This is most likely the case.

2. Check if your client really understands the answer and check if the answer is correct

Your client definitely should not receive a blank page (it indicates that the problem is 1).

Try to explicitly return a file by using Symfony\Component\HttpFoundation\File\File.

You also can set certain ZIP headers to a Response object manually - at least for debugging:

    // set example variables
    $filename = "zip-to-download.zip";
    $filepath = "/path"; // maybe save the response to a temp file for debugging purposes
    
    $response = $httpFoundationFactory->createResponse($psr7ApiResponse);
    $response->headers->set('Pragma','public');
    $response->headers->set('Expires',0);
    $response->headers->set('Cache-Control','must-revalidate, post-check=0, pre-check=0');
    $response->headers->set('Content-Description','File Transfer');
    $response->headers->set('Content-type','application/octet-stream');
    $response->headers->set('Content-Disposition','attachment; filename="'.$filename.'"');
    $response->headers->set('Content-Transfer-Encoding','binary');
    return $response;