lundi 24 février 2020

Laravel API returns file and client must show download dialog

I am developing an Laravel 5.3 API Brige to download some files to various systems. What I want to achieve:

  1. User clicks download button
  2. PHP web does a cURL post request to API
  3. Api response may be a file or a 404 HTTP Code
  4. Client browser shows file download dialog

APi method:

    $reportService = new ReportService($request->get('vRefGMS'));
    $reportData = $reportService->handle();
    if ($reportData) {
        $serverService = new NetServerService($reportData);
        $csvFile = $serverService->handle();
        if ($csvFile != null) {
            return response()->file($csvFile);
        } else {
            return abort(404);
        }
    } else {
        return abort(404);
    }

Now i will show you the code I had try.

PHP code in the web for the download:

    $uri = $this->getEndpointShow($this->reportCode, SELF::ENDPOINT_REPORT_DOWNLOAD);
    $file = $this->apiConnection->downloadReport($uri, $this->reportCode);
    if ($file) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        flush();
        readfile($file);
    } else {
        echo "alert('Can´t find a report file')";
    }

And the downloadReport method:

public function downloadReport($uri, $reportCode)
{
    if (!$reportCode) {
        throw new InvalidArgumentException("No report Code");
    }
    $cURLConnection = curl_init();
    curl_setopt($cURLConnection, CURLOPT_URL, self::BASE_API_URL . $uri);
    curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($cURLConnection, CURLOPT_POST, TRUE);
    curl_setopt($cURLConnection, CURLOPT_POSTFIELDS, "vRefGMS=$reportCode");
    curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . self::API_ACCESS_TOKEN
    ]);

    $response = curl_exec($cURLConnection);

    if ($response === false) {
        throw new Exception(curl_error($cURLConnection), curl_errno($cURLConnection));
    }

    curl_close($cURLConnection);

    return $response;
}

As you can see in the PHP code for the download I have a $file var which always comes blank $file = ''. I did also try on the api with return response()->download($csvFile) with the same result.

Is possible that I am missunderstanding concepts, but I cannot achieve the file download. How can get this file?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire