在sendGridnodejs中发送文件附件数组或多个文件附件

问题描述

如何将附件数组传递给 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,uploads\2NkGsPy936.jpg'

可能认为这两个文件一个。有什么想法吗?

解决方法

//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;
,

可能对其他人有用。

仅循环浏览文件并返回所需的值

// 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,type: file.mimetype,content: attachment,};
      });

然后附加到附件数组

....
attachments: attachments,