I uploaded a form data which contains an image file and some other fields. I uploaded the file image to my firebase cloud storage and added the other form data to my firebase firestore collection with a constructed URL of the file image I uploaded which was like (https://firebasestorage.googleapis.com/v0/b/${storageBucket key})/o/${filename}?alt=media
). my upload was successful but I got an error when I tried viewing the file image on my browser using the URL
{
"error": {
"code": 404,
"message": "Not Found. Could not get object",
"status": "GET_OBJECT"
}
}
Below is my RestApi Code:
exports.addType = (req, res) => {
const BusBoy = require('busboy');
const path = require('path');
const os = require('os');
const fs = require('fs');
const busboy = new BusBoy({headers: req.headers});
let fileName;
let fileToBeUploaded = {};
let fields = {};
busboy.on('field', (fieldname, data)=> {
fields[fieldname] = data;
})
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
const imageExtension = filename.split('.')[filename.split('.').length - 1];
fileName = `${Math.round(Math.random() * 10000000000000)}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), fileName);
fileToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
})
busboy.on('finish', ()=> {
let imageUrl;
admin.storage().bucket().upload(fileToBeUploaded.filepath, {
destination:`Type/${fileName}`,
resumable: false,
metadata: {
metadata: {
contentType: fileToBeUploaded.mimetype
}
}
})
.then(() => {
imageUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${fileName}?alt=media`;
return db.collection('Type').doc(fields.type);
})
.then(data => {
if(data.exists){
return res.status(400).json({error: `${fields.type} already exist`})
}
db.collection('Type').doc(fields.type).set({
type: fields.type,
category: fields.category,
details: fields.details,
imageUrl
})
})
.then(()=> {
return res.status(200).json({message: `${fields.type} has been added`});
})
.catch(err => {
return res.status(500).json({error: err.code});
})
})
busboy.end(req.rawBody);
}