如何解码 base64 附件文件 - Gmail API
How to decode base64 attachment file - Gmail API
我正在 javascript 中使用 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
});
}
我正在将此数据发送到 url,其中服务器代码是使用 php 完成的。
我正在使用以下代码解码 base64 数据并保存文件(仅适用于 png 图像文件):
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
终于找到解决办法了。添加了以下 php 代码:
$img = str_replace(' ', '+', $img);
$img = str_replace('_', '/', $img);
$img = str_replace('-', '+', $img);
解码和保存文件的新代码:
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.';
我正在 javascript 中使用 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
});
}
我正在将此数据发送到 url,其中服务器代码是使用 php 完成的。 我正在使用以下代码解码 base64 数据并保存文件(仅适用于 png 图像文件):
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
终于找到解决办法了。添加了以下 php 代码:
$img = str_replace(' ', '+', $img);
$img = str_replace('_', '/', $img);
$img = str_replace('-', '+', $img);
解码和保存文件的新代码:
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.';