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