【问题标题】:How to decode base64 attachment file - Gmail API如何解码 base64 附件文件 - Gmail API
【发布时间】: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


【解决方案1】:

终于解决了。添加了以下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.';

【讨论】:

    猜你喜欢
    • 2017-07-27
    • 2014-09-04
    • 2018-11-03
    • 2014-08-22
    • 2014-09-08
    • 2021-08-04
    • 2018-03-03
    • 1970-01-01
    • 2015-06-15
    相关资源
    最近更新 更多