When I trying to upload the file by the below code and able to do that in my local dev environment by when I use code and upload it to the server I am not able to get the response and I get an error - 500, Internal Server Error. I need help in this I have done some research but only get this link but unable to understand to resolve it.
https://cloud.google.com/storage/docs/exponential-backoff
Code For Upload
'use strict';
const {Storage}= require('@google-cloud/storage');
const config = require("./main");
const fs = require('fs')
const gcs = new Storage({
projectId: config.GCLOUD_PROJECT,
keyFilename: config.GCS_KEYFILE
});
const bucketName = config.bucketName
const bucket = gcs.bucket(bucketName);
function getPublicUrl(filename) {
return 'https://storage.googleapis.com/' + bucketName + '/' + filename;
}
let imageUpload = {};
imageUpload.uploadToGcs = (req, res, next) => {
if(!req.file) return next();
// Can optionally add a path to the gcsname below by concatenating it before the filename
const gcsname = req.file.originalname;
const file = bucket.file(gcsname);
const stream = file.createWriteStream({
metadata: {
contentType: req.file.mimetype
},
resumable: false
});
stream.on('error', (err) => {
req.file.cloudStorageError = err;
next(err);
});
stream.on('finish', () => {
req.file.cloudStorageObject = gcsname;
req.file.cloudStoragePublicUrl = getPublicUrl(gcsname);
next();
});
stream.end(req.file.buffer);
}
module.exports = imageUpload;
Route For upload
router.post("/uploadArticleImage",multer.single("image"), imgUpload.uploadToGcs,async function(req,res,next){
try {
let data = req.file;
//console.log(data)
if(data){
if (req.file && req.file.cloudStoragePublicUrl) {
data.imageUrl = req.file.cloudStoragePublicUrl;
}
// let imageUrl = data.imageUrl;
// console.log
res.send({status:true,message:"File Upload Sucessfull",imagedetails:data.imageUrl,token:null});
}
else{
res.send({status:false,message:"File Upload Unsucessfull",data:null,token:null});
}
}
catch (error) {
console.log(error);
return res.send({status:false,message:"Unsucessfull Server Error Occured",data:error,token:null});
}
});