Search code examples
node.jssendgridmulter

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


How do i pass an array of attachment to sendGrid's attachment Array.

multer handles the form,

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 handles the form:

upload.array('fileInput')

i can access the files and text fields as below

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');

Now, if i try to use it here i get error

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

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

probably it thought these two files upload are one. any ideas?


Solution

  • Might be useful for someone else.

    just loop through files and return values you need

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

    Then attach to attachment array

    ....
    attachments: attachments,