Uploading File to base64

I am using the SendMailer’s API to automatically send a user an email with an attachment after payment through stripe, but am struggling to upload the file because of Glitch’s asset URL. Currently, have it working and sending a regular email without the attachment. Any advice on executing the first two lines would be a huge help!
pathToAttachment = ${__dirname}/attachment.pdf;
attachment = fs.readFileSync(pathToAttachment).toString(“base64”);

const msg = {
  to: 'test@example.com',
  from: 'test@example.com',
  subject: 'Sending with SendGrid is Fun',
  text: 'and easy to do anywhere, even with Node.js',
  attachments: [
    {
      content: attachment,
      filename: "attachment.pdf",
      type: "application/pdf",
      disposition: "attachment"
    }
  ]
};

You can use fs.readFileSync("filename.pdf", "base64");

1 Like

Hi, thank you so much for responding! Just to clarify quickly, by “filename.pdf” do you mean the link that glitch provides?

1 Like

filename.pdf is a filename at your local storage, It used when your project has “that” file. Unfortunately, Every file that you uploaded to glitch, It will converted as RAW URL. Fortunately, You can request the URL and do this:

const { get } = require("https");

get("https://cdn.glitch.com/hsishdhsishdhwuahdhsj", response => {
  var data = [];
  response.on("data", chunk => data.push(chunk));
  response.on('end', () => {
     // Concat the arrayBuffer
     var buff = Buffer.concat(data);
     // Make it as base64
     var base64 = buff.toString("base64");
     // Do something....
  });
});
1 Like

Great, that is amazing thank you so so much!

1 Like

Hop! If you feels this code is too long for you, You can use node-fetch

const fetch = require("node-fetch");

fetch("https://cdn.glitch.com/abdisbaishfidjdhd").then(res => res.buffer()).then(BUFF => {
    // Make it as base64
    var base64 = BUFF.toString("base64");
    // Do something....
});

Also happy coding!

1 Like

That was absolutely perfect, this was the last thing not working on my platform. Thank you, happy coding as well!!

1 Like

Just to be clear of what @Yonle said, the Assets folder is a virtual folder that does not exist locally in a project. Files uploaded gets uploaded to Glitch’s CDN (cdn.glitch.com/*).

4 Likes