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

$ 데이터 변수는 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; 
} 
?> 

죄송합니다, 내 영어 나쁜

다음 정보가 도움이 될 수 있습니다.

파일

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

또는 대체 기능에 대한 MIME 내용 유형을 감지합니다.

클래스 파일 정보 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

Sory, 업데이트 후 "우리는이 파일을 열 수 없습니다 '참조 파일을 엽니 다. – Scaffold