【发布时间】:2016-11-21 22:44:32
【问题描述】:
我在 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
【问题讨论】:
-
不太确定,但不应该完全删除空格而不是用“+”号代替吗?
-
我尝试在不替换空格的情况下对其进行解码。但得到同样的错误
-
也试过
$data = base64_decode(chunk_split($img)); -
如果你在Linux下,你可以试试
cmp -l original.png uploaded.png吗? (或者可能是 Windows 下的 WinMerge 之类的工具。) -
我正在使用 ubuntu。我得到了输出
cmp: EOF on uploaded.png
标签: javascript php base64 gmail-api