in my application there is an input field to upload a CV.
What I need to do is when the file is selected, send that CV (pdf) as an attachment with an email to a user. For that Im using Sendgrid. In sendgrid we have to arrange the email option like below.
const fs = require('fs');
pathToAttachment = `file_path`;
attachment = fs.readFileSync(pathToAttachment).toString('base64');
const email = {
...
attachments: [
{
content: attachment,
filename: 'file_name',
type: 'application/pdf',
disposition: 'attachment'
}
]
...}
So here it is need to insert a file path to attach the pdf into email. I used Bootstrap for the input field. So I need to know, how can I insert the selected file's path. At the moment I can only get the select file using event.
pdfFile = event.target.files[0];
CodePudding user response:
In the example code, the attachment is loaded from the file system, however in this case the attachment is being entered via a web form with a file input. So, you don't need to fetch the file from the file system, but deal with it from the form submission.
When you submit the form with attachments, the attachment is sent to your server when the form is submitted. Attachments are normally sent in the multipart/form-data
format. From your code example, it looks like you are using Node.js, so I will also assume your server is an Express server. There are many ways to parse incoming multipart requests, one option is multer. To receive your file upload with multer and then pass it on to SendGrid would look like this:
const express = require('express');
const app = express();
const multer = require('multer');
const memoryStore = multer.memoryStorage();
const upload = multer({ storage: memoryStore });
app.post('/profile', upload.single("cv"), async function (req, res, next) {
// req.file is the "cv" file
const email = {
from: FROM,
to: TO,
text: "This has an attachment",
attachments: [
{
content: req.file.buffer.toString("base64"),
filename: "cv.pdf",
type: "application/pdf",
disposition: "attachment",
}
]
};
await sg.mail(email);
res.send("OK");
})
I chose memory storage for this file as it doesn't necessarily need to be written to disk. You may want to write the file to disk too though, and there are other considerations about using memory for this.
Because the file is in memory, req.file
has an object that describes the file and has a buffer
property that contains the contents. SendGrid needs you to base64 encode your attachments, so we call req.file.buffer.toString("base64")
.
This is a quick example, I recommend you read the documentation for multer to understand how your uploads work and how you can apply this to sending email attachments.