2017-04-10 55 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

相關問題