I'm trying to upload an image to firebase which works fine. The issue is if I try to use the api route with postman on an other pc the upload will not work. I investigated a lot but unfortunately it was not possible to solve this issue. I really don't understand why it's only working on my locale machine.
const Multer = require('multer')
const firebase = require('firebase')
const googleStorage = require('@google-cloud/storage')
const path = require('path')
const util = require('util')
let multer = Multer({
fileFilter: function(req, file, cb) {
checkFileType(file, cb)
},
storage: Multer.memoryStorage(),
limits: {
fileSize: 5 * 1024 * 1024
}
})
function checkFileType(file, cb){
const filetypes = /jpeg|jpg|png|gif/
const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimetype = filetypes.test(file.mimetype)
if(mimetype && extname){
return cb(null, true)
} else {
cb('Please provide only Images!')
}
}
const storage = googleStorage({
projectId: "mybucket",
keyFilename: "auth.json"
})
const bucket = storage.bucket("mybucket")
const uploadImageToStorage = (file) => {
let prom = new Promise((resolve, reject) => {
if (!file) {
reject('No image provided')
}
let newFileName = `${file.originalname}_${Date.now()}`
let fileUpload = bucket.file(newFileName)
const blobStream = fileUpload.createWriteStream({
metadata: {
contentType: file.mimetype
}
})
blobStream.on('error', (error) => {
reject('Something is wrong! Unable to upload at the moment.');
})
blobStream.on('finish', () => {
const url = util.format(`https://storage.googleapis.com/${bucket.name}/${fileUpload.name}`);
resolve(url)
})
blobStream.end(file.buffer)
})
return prom
}
module.exports = {
multer,
uploadImageToStorage
}
I fixed the issue.
const storage = googleStorage({
projectId: "mybucket",
credentials: require('../secret/auth.json')
})
I just removed the keyFilename
with credentials
. Is seems like to import my auth.json
as a modul was a better idea. I hope I will help someone with this solution. It work's fine for me now.