Firebase giving error : cannot read property 'ref' of undefined - javascript

I want to upload a photo in firebase storage and once its uploaded a downloadURL to be printed on console.
Photo is uploaded perfectly without any issue but in console instead of downloadURL , undefined is printed and an error thrown which states that 'TypeError: Cannot read property 'ref' of undefined'.
const file = $('#exampleInputFile').get(0).files[0]; // getting file to be uploaded
const name = (+new Date() + '-' + file.name); // creating filename with timestamp
const task = ref.child(name).put(file, {contentType: file.type}); //setting file
task.then( (snapshot) => console.log (snapshot.downloadURL))
.then(downloadURL => {
console.log(`Successfully uploaded file and got download link -
${downloadURL}`);
// once done trying to get downloadURL against this upload
})
.catch(error => {
// Use to signal error if something goes wrong.
console.log(`Failed to upload file and get link - ${error}`);
});
//or throw and error in console

save() {
this.storageref.child(this.file.name).put(this.file).then(snapshot => {
let image = snapshot.metadata.downloadURLs[0];
consol.log(image);
});
}

Related

Image upload functionality not working on deployed Heroku app but working on Localhost?

So I created my first big project: https://rate-n-write.herokuapp.com/
In brief, this is a blog app where the user can write reviews and publish them along with pictures.
I have used firebase as the database to store the articles. The app is working fine on localhost. Whenever I am trying to upload an image on Heroku, I get this error
The error is showing up in line number 8 of the following code (editor.js):
uploadInput.addEventListener('change', () => {
uploadImage(uploadInput, "image");
})
const uploadImage = (uploadFile, uploadType) => {
const [file] = uploadFile.files;
if(file && file.type.includes("image")){
const formdata = new FormData();
formdata.append('image', file);
//Error shows up here in the fetch line
fetch('/upload', {
method: 'post',
body: formdata
}).then(res => res.json())
.then(data => {
if(uploadType == "image"){
addImage(data, file.name);
} else{
bannerPath = `${location.origin}/${data}`;
banner.style.backgroundImage = `url("${bannerPath}")`;
}
})
const change_text = document.getElementById("uploadban");
change_text.innerHTML = " ";
} else{
alert("upload Image only");
}
}
This is just a snippet of the whole editor.js file.
Is it because I am trying to upload the file to the project directory? (server.js snippet below):
app.post('/upload', (req, res) => {
let file = req.files.image;
let date = new Date();
// image name
let imagename = date.getDate() + date.getTime() + file.name;
// image upload path
let path = 'public/uploads/' + imagename;
// create upload
file.mv(path, (err, result) => {
if(err){
throw err;
} else{
// our image upload path
res.json(`uploads/${imagename}`)
}
})
})
Do I need to use an online storage service like AWS S3?
Heroku is not suitable for persistent storage of data, the uploaded pictures would be deleted after a while (when the dyno is restarted) read this.
I would suggest using 3rd party object Storage services like
cloudinary or AWS S3

ffmpeg app using node occasionally crashes as file doesn't appear to be read correctly

I have an simple Node application that allows me to pass an AWS S3 URL link to a file (in this case video files). It uses the FFMPEG library to read the video file and return data like codecs, duration, bitrate etc..
The script is called from PHP script which in turn send the data to the Node endpoint and passes the Amazon S3 URL to node. Sometimes for no obvious reasons the video file fails to return the expected values regarding container, codec, duration etc... and just returns '0'. But when I try the exact same file/request again it returns this data correctly e.g container:mp4
I'm not sure but I think the script somehow needs the createWriteStream to be closed but I cannot be sure, the problem is the issue I have found doesn't happen all the time but sporadically so its hard to get to the issue when its difficult to replicate it.
Any ideas?
router.post('/', async function(req, res) {
const fileURL = new URL(req.body.file);
var path = fileURL.pathname;
path = 'tmp/'+path.substring(1); // removes the initial / from the path
let file = fs.createWriteStream(path); // create the file locally
const request = https.get(fileURL, function(response) {
response.pipe(file);
});
// after file has saved
file.on('finish', function () {
var process = new ffmpeg(path);
process.then(function (video) {
let metadata = formatMetadata(video.metadata);
res.send ({
status: '200',
data: metadata,
errors: errors,
response: 'success'
});
}, function (err) {
console.warn('Error: ' + err);
res.send ({
status: '400',
data: 'Something went wrong processing this video',
response: 'fail',
});
});
});
file.on('error', function (err) {
console.warn(err);
});
});
function formatMetadata(metadata) {
const data = {
'video' : metadata.video,
'audio' : metadata.audio,
'duration' : metadata.duration
};
return data;
}
// Expected output
{"data":{"video":{"container":"mov","bitrate":400,"stream":0,"codec":"h264","resolution":{"w":1280,"h":720},"resolutionSquare":{"w":1280,"h":720},"aspect":{"x":16,"y":9,"string":"16:9","value":1.7777777777777777},"rotate":0,"fps":25,"pixelString":"1:1","pixel":1},"audio":{"codec":"aac","bitrate":"127","sample_rate":44100,"stream":0,"channels":{"raw":"stereo","value":2}},"duration":{"raw":"00:00:25.68","seconds":25}}
// Actual output
{"data":{"video":{"container":"","bitrate":0,"stream":0,"codec":"","resolution":{"w":0,"h":0},"resolutionSquare":{"w":0,"h":null},"aspect":{},"rotate":0,"fps":0,"pixelString":"","pixel":0},"audio":{"codec":"","bitrate":"","sample_rate":0,"stream":0,"channels":{"raw":"","value":""}},"duration":{"raw":"","seconds":0}}
Note - this happens sporadically
You are not accounting for a failed fetch from AWS. You should check the status code of the response before you move on to your pipe.
const request = https.get(fileURL, function(response) {
if(response.statusCode == 200)
response.pipe(file);
else
// Handle error case
});

Could not upload files to Firestore with react

According to the firebase web documentation, it's possible to upload a base64 String with the following code
// Base64 formatted string
const message2 = '5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB';
uploadString(storageRef, message2, 'base64').then((snapshot) => {
console.log('Uploaded a base64 string!');
});
I tried to implement this example in react native with the following code
import storage from '#react-native-firebase/storage';
const uploadString = async () => {
let uploadTask = storage().ref().child('file_name').putString('5b6p5Y+344GX44G+44GX44Gf77yB44GK44KB44Gn44Go44GG77yB', 'base64');
uploadTask.on(
storage.TaskEvent.STATE_CHANGED,
null,
function (error) {
console.log('ERROR : ', error);
},
function () {
console.log('upload complete!');
});
}
I get an undefined error
ERROR : [Error: [storage/unknown] An unknown error has occurred.]
I also tried to upload base64 images, blob... nothing is working. Uploading files from the UI is however working. Should I enable something from the console? Am I importing the storage module correctly?

"No Credentials" error thrown when trying to access user settings in AWS through React

I’m trying to make a system in React where users can log in and change their credentials. I’m also trying to allow for users to save a profile picture. Whenever they upload a picture, it appears on the settings page but I can’t seem to find a way to fetch it again. To save the image file, this is what I’m using.
Storage.put("profile.png", file, {
contentType: "image/png"
})
And then I use Storage.get("profile.png") to fetch the image. The problem is when I try to fetch the image, I get an error thrown that says “No Credentials” and in the console, I see a message that says “cannot get guest credentials when mandatory signin enabled.” I also get the same “No Credentials” error thrown when I try to save the image. Does anyone know what’s going on? Here’s the code I used for saving and retrieving the image.
onProcessFile = async (e) => {
e.preventDefault();
let reader = new FileReader();
const file = e.target.files[0];
try {
reader.readAsDataURL(file);
} catch (err) {
alert(err);
}
reader.onloadend = () => {
setImage(reader.result)
};
const { id } = await Auth.currentUserPoolUser();
Storage.put("profile.png", file, {
contentType: "image/png"
})
.then(result => console.log(result))
.catch(err => alert(err));
};
getCurrentUser = async () => {
Storage.get("profile.png")
.then(url => {
var myRequest = new Request(url);
fetch(myRequest).then(function(response) {
if (response.status === 200) {
setImage(url)
}
});
})
.catch(err => alert(err));
}
My guess is you would need to set the right credentials on your bucket to be able to fetch the images when the user is signed in. Here is a link that goes a little deeper into this subject. Set up bucket credentials

Images not uploading to db in nodejs

I want to edit the image by using put method but when I give the path it shows 'filename' undefined .Image updating but i when skip to edit image then it shows me filename undefined
app.put('/about_update/:id',upload.single('avatar'),(req,res,next)=>{
console.log(res.file);
aboutus.findById(req.params.id,(err,data2)=>{
if(err){
return res.send(err.message, '404 error from server');
}
data2.personName = req.body.personName;
data2.designation = req.body.designation;
data2.content = req.body.content;
data2.avatar = req.file.filename;
data2.save(function(err){
if(err){
res.send(err.message, 'err from server');
}else{
res.json({message:'updated successfully'});
}
})
})
})
error:
events.js:183
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'filename' of undefined
at aboutus.findById (/var/www/html/gis-react-version/api/server.js:147:33)
at /var/www/html/gis-react-version/api/node_modules/mongoose/lib/model.js:4451:16
at process.nextTick (/var/www/html/gis-react-version/api/node_modules/mongoose/lib/query.js:2476:28)
if (req.file) {
data.personName = req.body.personName;
data.designation = req.body.designation;
data.content = req.body.content;
data.avatar = req.file.filename;
}else{
data.personName = req.body.personName;
data.designation = req.body.designation;
data.content = req.body.content;
}
aboutus.findByIdAndUpdate(req.params.id, {
$set: {data}
}).then(() => {
res.json({message:'updated successfully'});
}, (err) => {
res.json({message:'err from server'});
})
body-parser handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading images).
Thus it is showing this issue.
In order to use that ,you can simply use multer package.

Categories