1
votes

I am trying to construct an API end point to receive small Audio files from the user and upload it to firebase storage. I am using multer to handle the form data but when testing with postman i'm not sure if upload.single('file') is working since req.body and req.file is undefined. am I doing something wrong?

I read a lot of stackoverflow threads about this but non of them worked

code:

const functions = require('firebase-functions');
const googleStorage  = require('@google-cloud/storage');
const express = require('express');
const cors = require('cors');
const compression = require("compression");
const saltedMd5 = require("salted-md5");
const multer = require("multer");
const path = require("path");

const app = express();

const admin = require('firebase-admin');
admin.initializeApp({
  storageBucket: <bucket address>
});
app.locals.bucket = admin.storage().bucket(<bucketName>);
const db = admin.firestore();

app.use(cors({ origin: true }));
app.use(express.urlencoded({extended: true}));
app.use(express.json());


const upload = multer({
  storage: multer.memoryStorage(),
});


app.post("/upload", upload.single("file"),  (req, res) => {
  console.log(req.file); //undefined
  console.log(req.files); //undefined
  console.log(req.body); //[Object: null prototype] {}
  console.log(req.name); //undefined
  const name = saltedMd5(req.file.originalname, "SUPER-S@LT!");
  const fileName = name + path.extname(req.file.originalname); //error 'originalname' of undefined
  app.locals.bucket
    .file(req.file)
    .createWriteStream()
    .end(req.file.buffer)
    .then((i) => res.send("done"))
    .catch((e) => res.send(e));
});

Request in postman screenshot

1
I can't spot anything weird in the backend code and the request from Postman seems ok. What does req.headers output if you log it?Maxim Orlov

1 Answers

0
votes

Turns out Firebase and multer don't go well together. I referred to this article which explains why multer does not work and how to achieve the same goal with Busboy.

https://mikesukmanowsky.com/firebase-file-and-image-uploads/