在 sendGrid (nodejs) 中发送文件附件数组或多个文件附件

Send array of file attachment or multiple file attach in sendGrid (nodejs)

如何将附件数组传递给 sendGrid 的附件 数组。

multer处理表格,

HTML

 <div class="file-field input-field">
        <div class="btn btn-small z-depth-0">
          <span><i class="small material-icons">attach_file</i></span>
          <input type="file" id="fileInput" name="fileInput" multiple />
        </div>
        <div class="file-path-wrapper">
          <input class="file-path" type="text" placeholder="Attach a file?">
        </div>
     </div>

Multer 处理表格:

upload.array('fileInput')

我可以如下访问文件和文本字段

const files = req.files;
  const { email, content, subject, cc } = req.body;
  
  let allFilePath;
  let allFileOriginalName;
  let allFileType;

  Trying to loop here...  

  let res1 = files.map((file) => file.path);
  let res2 = files.map((file) => file.originalname);
  let res3 = files.map((file) => file.mimetype);

  allFilePath = res1;
  allFileOriginalName = res2;
  allFileType = res3;

  console.log(allFilePath, allFileType, allFileOriginalName);

  const pathToAttachment = `${allFilePath}`;
  const attachments = fs.readFileSync(pathToAttachment).toString('base64');

现在,如果我尝试在这里使用它,我会收到错误消息

        ...
        attachments: [
            {
              content: [attachments],
              filename: [allFileOriginalName],
              type: [allFileType],
              disposition: 'attachment',
            },
          ],

 Error: ENOENT: no such file or directory, open 'uploads\athpyCXtW.jpg, uploadsNkGsPy936.jpg'

可能它认为上传的这两个文件是一个。有什么想法吗?

可能对其他人有用。

只需遍历文件和 return 您需要的值

// Loop through files to return some fields
      const attachments = files.map((file) => {
        const pathToAttachment = file.path;
        const attachment = fs.readFileSync(pathToAttachment).toString('base64');
        return {
          filename: file.originalname,
          disposition: 'attachment',
          type: file.mimetype,
          content: attachment,
        };
      });

然后附加到附件数组

....
attachments: attachments,
//files is array of image Url 
     let attachment = await Promise.all(files.map(val => imageToBase64(val)))
        attachments = attachment && attachment.map(attachment => ({
          filename: 'attachment.png',
          disposition: 'attachment',
          type:'application/image',
          content: attachment
        }));
      const body = await sgMail.send({
      to: email,
      from,
      subject: "subject ",
      html: "helloo",
      ...(
        attachments && attachments.length && {
          attachments: attachments
        }
      )
    });
    return body;