2016-07-19 2 views
1

を私はJavaScriptでGmailのAPI関数を使用しています:- GmailのAPI

var request = gapi.client.gmail.users.messages.attachments.get({ 
    'userId': 'me', 
    'messageId': 'MyMessageId', 
    'id': 'MyAttachmentId' 
}); 

request.execute(function(resp) { 
    var dd = new FormData(); 
    //here resp.result.data is the base64 data of the attachment file 
    dd.append("img_data", JSON.stringify(resp.result.data)); 

    fetch("http://my-url",{ 
    method: 'post', 
    body: dd 
    }); 
} 

私は、サーバーコードはPHPを使用して行われたURLにこのデータを送信しています。私は(だけで画像ファイルをPNG形式のため)base64のデータをデコードすると、ファイルを保存するには、次のコードを使用しています :

define('UPLOAD_DIR', './'); 
$img = json_decode($_POST['img_data']); 
$img = str_replace('data:image/png;base64,', '', $img); 
$img = str_replace(' ', '+', $img); 
$data = base64_decode($img); 
$file = UPLOAD_DIR . uniqid() . '.png'; 
$success = file_put_contents($file, $data); 
print $success ? $file : 'Unable to save the file.'; 

すべてが正常に動作しますが、保存した画像ファイルが破損しているとエラーが表示されます。Fatal error reading PNG image file: Decompression error in IDAT

+0

かなりわからないが、空白はすべて削除ではなく」で置き換えるべきではありません。

$img = str_replace(' ', '+', $img); $img = str_replace('_', '/', $img); $img = str_replace('-', '+', $img); 

新しいコードをデコードすると、ファイルを保存するには、次のPHPコードを追加しました'兆候? – Arnauld

+0

空白を置き換えずにデコードしようとしました。あなたがLinuxでなら ' –

+0

を取得しても '$データ= BASE64_DECODE(chunk_split($のIMG))を試してみましたか? (またはWindowsの下でWinMergeのようなツールかもしれません) –

答えて

1

最後に解決策を得ました。 +その

define('UPLOAD_DIR', './'); 

$img = json_decode($_POST['img_data']); 
$img = str_replace(' ', '+', $img); 
$img = str_replace('_', '/', $img); 
$img = str_replace('-', '+', $img); 
$data = base64_decode($img); 
$file = UPLOAD_DIR . uniqid() . '.png'; 
$success = file_put_contents($file, $data); 
print $success ? $file : 'Unable to save the file.';