无法打开从 base64 字符串 Gmail 下载的文件 API

cannot open downloaded file from base64 string Gmail API

我正在从 Gmail API 下载一个使用 base64 字符串的附件。当我使用 Windows 打开下载的文件时,我看到错误 'We can't open this file'。我检查了 $data 数组中的 headers,它们是正确的,我还检查了下载文件的大小,这也是正确的大小。

我使用以下方式下载文件:

$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;

$image 字符串是有效的,因为如果我使用下面的图像正确显示:

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

如何修复文件下载?

$data 变量是 base64_encode 资源。

<?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;
}
?>

对不起,我的英语不好

以下信息可能会有帮助。

检测文件的 MIME 内容类型

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

或替代函数。

class 文件信息 http://us2.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() 函数 http://php.net/manual/en/function.file-get-contents.php

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

示例代码。

$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.'">';