1
votes

I'm currently trying to store all gmail emails attachement, witch are encoded in base64url (https://developers.google.com/gmail/api/v1/reference/users/messages/attachments).

gmail.users.messages.attachments.get({
    'auth': auth,
    'userId': 'me',
    'id': 'attachementId',
    "messageId": 'messageId'
}, function(err, response, seg) {
    if (err) {
       //
    } else {
        var base64_attachement = response.data.replace(/-/g, '+').replace(/_/g, '/').replace(/ /g, '+');
        var buffer = new Buffer(base64_attachement, "base64");
        var attachementDecode = buffer.toString();
    }
});

But when i store the message in a file or in my S3 and I try to read it (with the good format) I can't see anything, and images editors as gimp say thats the image is corrupted. What am I doing wrong ? I'm really lost how can I decode a google attachement in base64url format ?

2

2 Answers

6
votes

I get also attachment from gmail and success to save them : set the base-64 in Blob object and then you could use FileSaver library to save the file in your computer easily.

Code:

 var base64=(response.data).replace(/_/g, '/'); //Replace this characters 
 base64=base64.replace(/-/g, '+');
 var base64Fixed = fixBase64(base64);
 var blob = new Blob([base64Fixed], { type: "image/png" } ); //set your file type!
 saveAs(blob,"name of file"); //Using FileSaver library 


function fixBase64(binaryData) {
  var base64str = binaryData// base64 string from  thr response of server
  var binary = atob(base64str.replace(/\s/g, ''));// decode base64 string, remove space for IE compatibility
  var len = binary.length;         // get binary length
  var buffer = new ArrayBuffer(len);         // create ArrayBuffer with binary length
  var view = new Uint8Array(buffer);         // create 8-bit Array

  // save unicode of binary data into 8-bit Array
  for (var i = 0; i < len; i++)
      view[i] = binary.charCodeAt(i);

 return view;
}

Hope that it's will help you. Good luck

1
votes

A simple by referring to @OriEng 's solution and use js-base64

# npm i js-base64
const Base64 = require('js-base64')
function decodeBase64(str) {
  str = str.replace(/_/g, '/').replace(/-/g, '+') // important line
  return Base64.atob(str)
}