在我的应用程序中有一个输入字段来上传简历。
我需要做的是,当文件被选中时,将简历(pdf)作为附件发送给用户。为此,我使用Sendgrid。在sendgrid中,我们必须像下面这样安排电子邮件选项。
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'
}
]
...}
所以这里需要插入一个文件路径来将pdf附加到电子邮件中。我在输入字段中使用了Bootstrap。因此,我需要知道,如何插入所选文件的路径。目前,我只能使用事件获取select文件。
pdfFile = event.target.files[0];
发布于 2022-04-07 06:22:46
在示例代码中,附件是从文件系统加载的,但是在这种情况下,附件是通过带有文件输入的web表单输入的。因此,您不需要从文件系统中获取文件,而是从表单提交中处理它。
当您提交带有附件的表单时,附件将在表单提交时发送到您的服务器。附件通常以multipart/form-data
格式发送。从您的代码示例来看,它看起来像是在使用Node.js,所以我还假设您的服务器是一个Express服务器。解析传入的多部分请求有许多方法,其中一个选项是穆特。若要通过multer接收您的文件上传,然后将其传递给SendGrid,如下所示:
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");
})
我为这个文件选择了内存存储,因为它不一定需要写入磁盘。不过,您可能也希望将该文件写入磁盘,为此使用内存还有其他注意事项。
因为文件在内存中,所以req.file
有一个描述文件的对象,并具有一个包含内容的buffer
属性。SendGrid需要您对附件进行base64编码,因此我们调用req.file.buffer.toString("base64")
。
这是一个快速的例子,我建议您阅读穆特的文献资料以了解您的上传是如何工作的,以及如何将其应用于发送电子邮件附件。
https://stackoverflow.com/questions/71776750
复制相似问题