[英]cannot open downloaded file from base64 string Gmail API
我正在從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>";
如何修復文件下載?
$ 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/zh/function.file-get-contents.php
base64_encode()函數http://php.net/manual/zh/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.'">';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.