node.jsexpressaxiosnodemailerreact-typescript

How to export a xlsx file from frontend (react) to backend (express), and then send it to email?


So, I needed a function to convert data from an array containing arrays of objects into a sheet, and managed to do so with the xlsx lib. Now I need to send it appended to an email and it worked fine with nodemailer (the email is, at least, being sent), but after converting an array with more than 75 objects with a 'for' loop and encoding it to base64, the payload that goes to the backend request got too big and returned an error 413.

I thought about sending the .xlsx file directly to the backend instead of converting it + decoding the base64, so I researched and saw that I could use form-data + axios in the frontend, and multer in the backend, but apparently I'm not managing to do it correctly cause the email is being sent with an empty sheet.

Below is how I coded it, would be grateful if someone could help =]

[Front End]

const exportDataToSheet = async (email: string, dataArray: any) => {
  try {
    const listProducts = [];
    for (const object of dataArray.objects) {
            const dataObject = await getData(data.nr_pedido, data.cd_filial);
            listProducts.push(dataObject)
    }

    const workBook = XLSX.utils.book_new();
    const excelHeaders: string[] = [
      "Product",
      "Network",
      "Branch",
      "Branch name",
    ];

    const productData = [];
    for (const product of listProducts) {
      const productDetails = [
        `${product?.data[0]?.nr_product ?? "-"}`,
        `${product?.data[0]?.id_branch ?? "-"}`,

        //...a lot of more info...

      ]
      productData.push(productDetails)
    }
    
    productData.unshift(excelHeaders);

    const workSheet = XLSX.utils.aoa_to_sheet(productData);
  
    XLSX.utils.book_append_sheet(workBook, workSheet, "Infos on the products");

    const file = XLSX.writeFile(workBook, {bookType:'xlsx'});

    const formData = new FormData();

    formData.append('file', file);

    axios.post('http://localhost:3001/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => {
      console.log('File successfully sent.');
})
.catch(error => {
  console.error(error);
    })

    await requestMailer({
      email: email,
      model: "exportProductData",
      filename: `data_products.xlsx`,
    });
  } catch (error) {
    showAlert(error.response ? error.response.data.message : error.message, "error");
  }
}

[Back End]

export default class EmailNodeMailerService {
  static async sendEmail(req: Request) {
    const express = require('express');
    const multer = require('multer');
    const upload = multer({dest: './uploads'});
    const app = express();
    let file;

    app.post('/upload', upload.single('arquivo'), (req, res) => {
      file = req.file;
      console.log('File received: ', file.originalName);
      res.send('File successfully sent.')
    })

//...various lines regarding node mailer...

            mailOptions.attachments = [
              {
                filename: filename ? filename : 'product_data.xlsx',
                content: file,
                contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
              }
            ];
          }
          
//...more code regarding node mailer...

    } catch (error) {
      throw new Error(error);
    }
  }
}

Solution

  • The below statement in the frontend appends the file in the name 'file'. Now in the backend, multer upload should reference the same. At present it refers to 'arquvio'.

    formData.append('file', file); //frontend
    
    upload.single('arquivo') //backend
    

    One of the two changes below is required:

    Change 1:

    formData.append('arquivo', file); //frontend
    
    upload.single('arquivo') //backend
    

    Change 2:

    formData.append('file', file); //frontend
    
    upload.single('file') //backend
    

    Note: I have not tested and confirmed this particular scenario, however it has been documented so in Multer NPM. For a quick reference, please see the quote below. For more, please see Multer NPM given in the citation.

    ...Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the name field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren't the same in the HTML form and on your server, your upload will fail:...

    Citation:

    Multer