【问题标题】:cannot open downloaded file from base64 string Gmail API无法从 base64 字符串 Gmail API 打开下载的文件
【发布时间】:2017-09-05 00:31:50
【问题描述】:

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

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

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

如何修复文件下载?

【问题讨论】:

    标签: php base64 gmail-api readfile


    【解决方案1】:

    $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

    或替代功能。

    类文件信息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.'">';
    

    【讨论】:

    • 我已经可以显示图像了,问题是下载图像,下载后我打开文件我看到'我们无法打开这个文件'
    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 2016-04-14
    • 2019-01-08
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多