I’m working on a Node.js application where I need to parse and save multipart form data sent via HTTP requests. I’m using the built-in http module to handle requests, and I’ve managed to parse the multipart form data successfully. However, I’m encountering difficulties when trying to save files locally.
Here’s the function responsible for parsing the multipart form data and attempting to save the file:
const fs = require('fs');
function parseMultipartFormData(req) {
let body = req.body;
const boundary = body.split(/r?n|r/, 1)[0];
body = body.split(boundary);
body.shift();
body.pop();
let parsedData = {};
for (let part of body) {
part = part.trim();
if (part.includes("filename")) {
const fileRegex = /name="(.+)"; filename="(.+)"r?nContent-Type: (w+/w+)(?:r?n)*([sS]*)/;
const match = fileRegex.exec(part);
if (match) {
parsedData[match[1]] = {
filename: match[2],
contentType: match[3],
contentData: match[4],
};
}
} else {
part = part.replace(/r?n|r/g, "");
const regex = /name="(.+)"(.+)/;
const match = regex.exec(part);
if (match) {
parsedData[match[1]] = match[2];
}
}
}
// Write file if productImage exists
if (parsedData.productImage && parsedData.productImage.contentData) {
const imageData = parsedData.productImage.contentData;
const filename = parsedData.productImage.filename;
fs.writeFile(filename, imageData, "binary", (err) => {
if (err) {
console.error('Error saving image:', err);
} else {
console.log('Image saved successfully.');
}
});
}
return parsedData;
}
I’ve deliberately avoided using multer or any similar third-party libraries for this task.
I’ve noticed that the file doesn’t get saved properly, and I’m not sure how to handle the file data correctly. Can anyone provide guidance on how to properly handle and save files in this scenario?
Additionally, here’s how the parsed form data looks like after being processed:
{
"productName": "Carolyn Jordan",
"productDescription": "Eligendi enim conseq",
"productPrice": "82",
"productImage": {
"filename": "logoWhiteBgSocial.png",
"contentType": "image/png",
"contentData": "�PNG IHDRLL�� pHYs��sRGB���gAMA���a8zIDATx���uTW����=��vG@w�� ... (truncated)"
}
}
i tried to see if the data is encoded or compressed in gzip, defalte…ect but i couldn’t find anything helpful in the request headers.