在我的應用程式中有一個輸入欄位來上傳簡歷。
)">
我需要做的是,在選擇檔案后,將該簡歷(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 作為輸入欄位。所以我需要知道,如何插入所選檔案的路徑。目前我只能使用事件獲取選擇檔案。
pdfFile = event.target.files[0];
uj5u.com熱心網友回復:
在示例代碼中,附件是從檔案系統加載的,但在這種情況下,附件是通過帶有檔案輸入的 Web 表單輸入的。因此,您不需要從檔案系統中獲取檔案,而是從表單提交中處理它。
當您提交帶有附件的表單時,附件會在表單提交時發送到您的服務器。附件通常以multipart/form-data格式發送。從您的代碼示例中,您似乎正在使用 Node.js,因此我還將假設您的服務器是 Express 服務器。決議傳入的多部分請求的方法有很多,其中一種方法是multer。要使用 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").
這是一個簡單的示例,我建議您閱讀multer 的檔案以了解您的上傳如何作業以及如何將其應用于發送電子郵件附件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/461068.html
