2017-04-10 57 views
0

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

我使用下面的下载文件:

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

如何解决文件下载?

回答

0

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

我已经可以显示图像,这个问题是下载图像,其下载后,我打开我看看“我们不能打开此文件” – user3312792

+0

索里,更新后的文件。 – Scaffold

相关问题