Search code examples
phpbase64gmail-apireadfile

cannot open downloaded file from base64 string Gmail API


I am downloading an attachment using a base64 string from Gmail API. When I open the downloaded file using Windows, I see the error 'We can't open this file'. I have checked the headers from $data array and they are correct, I have also checked the size of the file downloaded and this is also the correct size.

I download the file using the below:

$data = $json['data'];

$data = strtr($data, array('-' => '+', '_' => '/'));

$image = base64_decode($data);

header('Content-Type: image/jpg; name="crop-1.jpg"');
header('Content-Disposition: attachment; filename="crop-1.jpg"');
header('Content-Transfer-Encoding: base64');
header('X-Attachment-Id: f_j1bj7er60');

readfile($image);

// I have also tried
echo $image;

The $image string is valid because if I use the below the image displays correctly:

echo "<div>
       <img src=\"data:image/jpg;base64, $image\" />
      </div>";

How do I fix the file download?


Solution

  • $data variable is base64_encode resource.

    <?php
    $decoded = base64_decode($data);
    $file = 'download_file.jpg';
    file_put_contents($file, $decoded);
    
    if (file_exists($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));
        readfile($file);
        unlink($file);
        exit;
    }
    ?>
    

    Sorry, my english bad

    The following information may be helpful.

    Detect MIME Content-type for a file

    http://php.net/manual/en/function.mime-content-type.php

    or alternative function.

    class file info https://www.php.net/manual/en/fileinfo.constants.php

    function _mime_content_type($filename) {
        $result = new finfo();
    
        if (is_resource($result) === true) {
            return $result->file($filename, FILEINFO_MIME_TYPE);
        }
    
        return false;
    }
    

    file_get_contents() function http://php.net/manual/en/function.file-get-contents.php

    base64_encode() function http://php.net/manual/en/function.base64-encode.php

    example code.

    $imageData = base64_encode(file_get_contents($image));
    
    // Format the image SRC:  data:{mime};base64,{data};
    $src = 'data: '.mime_content_type($image).';base64,'.$imageData;
    
    // Echo out a sample image
    echo '<img src="'.$src.'">';