Usecase: I need to upload an .xlsx file to a cloud function API parse the data to json form and upload it to Firebase Firestore. I am using typescript for writing cloud functions.
I read about multer and came to the understanding that using multer with firebase has some issues. Busboy was the other option.
And went through this example code : https://gist.github.com/tonkla/5e893aa8776923ad6a2c9c6b7c432f3d
The headers['content-type'] I am sending to busboy is 'application/x-www-form-urlencoded'
and tried to imply it in my code.
To check the file upload I used postman to upload the file to my url but its going into request timed out.
export const fileUpload = functions.https.onRequest(async (req, res) => {
const data = await parseMultipartFormData(req.rawBody,req.headers['content-type'])
console.log("Data from busboy:"+data)
const workbook = xlsx.read(data,{type: 'buffer'})
const jsonRows = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
res.status(200).json(jsonRows)
});
function parseMultipartFormData(rawBody, headers) {
return new Promise((resolve, reject) => {
const buffers : any[]= []
const busboy = new busboyMain({
headers: { 'content-type': headers },
})
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
file.on('data', data => {
buffers.push(data);
})
file.on('end', () => {
resolve(Buffer.concat(buffers));
})
})
busboy.on('error', error => reject(error))
busboy.end(rawBody)
})
}