File downloaded with Google Drive API corrupt? Using service Account

61 views Asked by At

I have a Form and upload files to Google drive like this (php):

            $fileMetadata = new Google\Service\Drive\DriveFile(
                array(
                    'name' => $bestandsnaamInDoelmap,
                    'mimeType' => mime_content_type($file_tmp),
                    'parents' => array($bovenliggendeMapId),
                )
            );
            try {
                $content = file_get_contents($file_tmp);
                $file = $service->files->create(
                    $fileMetadata,
                    array(
                        'data' => $content,
                        'mimeType' => mime_content_type($file_tmp),
                        'uploadType' => 'multipart'
                    )
                );
            } catch (Exception $e) {
                return "Fout in aanmaken bestand: " . $e->getMessage();
            }

Then I try to download the file with:

try {
        return $service->files->get($fileId, array('alt' => 'media'));
    } catch (Exception $e) {
        return "Fout in zoeken naar bestand " . $fileId . ": " . $e->getMessage();
    }

I checked filesize from file sent to drive and filesize coming back: are the same. Uploading the downloaded file shows also the same size BUT

when I have a small textfile with text 'small' it opens and shows me text 'sm'.

And with binary files (pdf/jpg/png etcetera) the downloaded file is corrupt.

For downloading i use in PHP:

    // Haal het bestand op met behulp van de fileID
    $response = get_file($downloadfileId);

    $fileContent = $response->getBody()->getContents();

    header('Content-Description: File Transfer');
    header('Content-Type: ' . $mimeType);
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . strlen($fileContent)));
    
    // Stuur de gegevens naar de browser
    echo $fileContent;

    exit;

What is going wrong here? If I add 3 to strlen($fileContent) in the example above the textfile shows me 'small'. For binary files that does not help.

Hope someone can help me.

Upload file to Drive with Google Drive api (from a website, using service account)

Download the file again from the website.

This all on a Joomla website with PHP 8.1 and PHP 8.1 google drive api.

File should be equal, not corrupted.

0

There are 0 answers