Arun D
Arun D

Reputation: 2387

How to decode base64 attachment file - Gmail API

I am using the Gmail API function in javascript:

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
  });
}

I am sending this data to a url, where the server code is done using php. I am using the following code to decode the base64 data and to save the file(Just for png image files):

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.';

Everything works fine, but the saved image file is corrupted and shows the error: Fatal error reading PNG image file: Decompression error in IDAT

Upvotes: 1

Views: 1836

Answers (1)

Arun D
Arun D

Reputation: 2387

Finally got the solution. Added the following php code:

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

The new code to decode and to save the file:

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.';

Upvotes: 1

Related Questions