How to add image and data into firebase - javascript

I want to send/add notification data in database that contains image with some text data so I am not able to add this data in firebase. I tried some code for only data insertion, but it doesn't work and How do I add image in firebase?
I am adding database which is made manually for notification. I want to add further more notifications with image
database
This is my html form
<form method=post enctype="multipart/form-data">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label>Title</label>
<input type="text" id="title" class="form-control" placeholder="Company" >
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Image</label>
<input type="image" class="form-control" placeholder="Image">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Redeem Steps</label>
<input type="text" id="redeem" class="form-control" placeholder="Redeem Steps">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Description</label>
<textarea rows="5" id="description" class="form-control" placeholder="Here can be your description"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" >
Image 1 <span style="color:red">*</span><!--<input type="file" id="image" name="img1" required>-->
</div>
</div>
<button type="submit" id="submitBtn" class="btn btn-info btn-fill pull-right" onclick="submitclick()">Send notification</button>
<div class="clearfix"></div>
</form>
this is js file
var title=document.getElementById("title");
var redeem=document.getElementById("redeem");
var description=document.getElementById("description");
var image=document.getElementById("image");
var submitBtn=document.getElementById("submitBtn");
var Id=1;
function submitclick(){
var firebaseref=firebase.database().ref();
var messagetitle=title.value;
var messageredeem=redeem.value;
var messagedescription=description.value;
//var messageimage=image.value;
console.log(messagetitle);
console.log(messageredeem);
console.log(messagedescription);
//console.log(messageimage);
//firebaseref.child("notification").set("vinit");
//firebaseref.child("notification").set("2");
//firebaseref.child("notification").set("messagedescription");
//firebaseref.child("notification").set("messageimage");
firebase.database().ref('notification/'+Id).set({
title : messagetitle,
redeem : messageredeem,
description : messagedescription
image : messageimage
});
console.log(Id);
Id++;
console.log(Id);
}

You cannot upload image directly into the firebase database. You have to upload the image into the firebase storage first, then you can store the image name/location/downloadUrl in the database if you want. Altough, store the download url is not the best practice.
const file = ...
const metadata = { contentType: 'image/jpeg' }; // or whatever you want
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`images/${file.name}`).put(file, metadata);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, snapshot => {
// If you want to show upload progress, do whatever you want with progress...
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED:
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING:
console.log('Upload is running');
break;
}
}, error => {
console.log(error);
}, () => {
// upload finished with success, you can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
console.log(downloadURL);
});
});
If you want to store the downloadUrl into the databse then you have to store tha downloadUrl into a variable or put the database set into the upload finished callback.
The database set part should work with this way:
// The id should foloow your database structure,
// based on your posted image, should look like this:
// `noti_${id}` where the id is a number.
firebase.database().ref(`notification/${id}`).set({
...uploadData,
image: downloadUrl
});
Also, I hardly recommend you to use async await to handle promises and use cloud firestore instead of realtime database.

Related

Form with recaptcha redirect after submission

I'm trying to learn express/nodejs and implement a form, where after recaptcha you can click and download a file. But after form submission I'm being redirected to localhost/submit with only status code on the page. This is driving me crazy, I just want to enable download button after passing recaptcha. I believe this is obvious, but not for me.
server.js file
// Load Node modules
var express = require("express");
const fetch = require("isomorphic-fetch");
// Initialise Express
var app = express();
// Render static files
app.use(express.static("public"));
// Port website will run on
app.listen(8080);
// To accept HTML form data
app.use(express.urlencoded({ extended: false }));
// Here, HTML form is submit
app.post("/submit", (req, res) => {
const name = req.body.name;
// getting site key from client side
const response_key = req.body["g-recaptcha-response"];
// Put secret key here, which we get from google console
const secret_key = "6LdGoQohAAAAAJe6wa_-xayew_ht3N6Lm-kSdbW9";
console.log(res);
// Hitting POST request to the URL, Google will
// respond with success or error scenario.
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`;
// Making POST request to verify captcha
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
// google_response is the object return by
// google as a response
if (google_response.success == true) {
// if captcha is verified
return res.sendStatus(200);
} else {
// if captcha is not verified
console.log(google_response);
return res.sendStatus(400);
}
})
.catch((error) => {
// Some error while verify captcha
return res.json({ error });
});
});
html form
<form class="main-form" action="/submit" method="post" id="myForm">
<div class="form-row">
<div class="form-element">
<label for="form-delivery">Номер поставки:</label>
<input type="text" name="delivery" required id="form-delivery" />
</div>
<div class="form-element">
<label for="form-num">Номер ТТН:</label>
<input type="text" name="delivery2" id="form-num" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-date" req>Дата формирования:</label>
<input type="date" name="delivery3" id="form-date" required />
</div>
<div class="form-element">
<label for="form-client">Клиент:</label>
<input type="text" name="delivery4" id="form-client" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-car">Гос. номер:</label>
<input type="text" name="delivery5" id="form-car" />
</div>
<div class="form-element">
<label for="form-cert">Номер сертификата:</label>
<input type="text" name="delivery6" id="form-cert" />
</div>
</div>
<div id="g"></div>
<button class="download-link" type="submit">Скачать</button>
</form>

File Upload With Vanilla Javascript (Form Data Object always empty)

I have been trying to upload an image to the server for a few days now. But server does not receive any image because form data object is always empty. I then tried to use a library called dropzone for image upload and it worked. But I dont want to use any library. Can somebody please help me understand why form data object is always empty when I send it? I would really appreciate it cuz it will also help me in future. Thank you.
Html Code
<form class="editProfileForm" encType="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="col-12 mt-3">
<div class="text-left">
<label for="certificateImg">CertificateImage</label>
</div>
<input id="certificateImg" type="file" />
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center mt-3 mb-5">
<button class="saveBtn btn btn-primary btn-brand-lg" type="button">Save</button>
</div>
</div>
</div>
</form>
JS Code
const editProfileForm = document.querySelector('.editProfileForm');
const saveBtn = document.querySelector('.saveBtn');
saveBtn.addEventListener('click', () => {
let img = document.getElementById('certificateImg').files[0];
let formData = new FormData();
formData.append('img', img);
console.log(formData);
const doctorUpdateGeneral = async () => {
try {
const response = await axios.put(
'API here',
{
certificate: formData,
},
{
headers: {
Authorization: token,
},
}
);
console.log(response);
window.location.reload();
console.log(pmdc);
} catch (err) {
console.log(err);
}
};
doctorUpdateGeneral();
});
Change the encType attribute to enctype in the form element tag

Get Image URL from Google Drive to Google Sheet based on file name

Good day!
I am trying to access the Google Drive, and get an specific image file based on profile number from web app. For example, if I input a profile number and details on the web app, after submit, it will append the details on the google sheet, and I am trying to search the image in the Google Drive and put its URL on the last column.
Here is my html code:
<body>
<!-- CONTAINER -->
<div class="container-md">
<!-- HEADING -->
<h3 style="color:green;">User Data</h3>
<!-- CONTENT -->
<div class="form-row">
<div class="form-group col-md-2">
<input id="rnum" class="form-control" type="text" placeholder="Profile Number" pattern="^\d{5}$" required>
</div>
</div>
<!-- FULL NAME -->
<div class="form-row">
<div class="form-group col-md-3">
<input id="fname" class="form-control" type="text" placeholder="First Name" required>
</div>
<div class="form-group col-md-3">
<input id="mname" class="form-control" type="text" placeholder="Middle Name" required>
</div>
<div class="form-group col-md-3">
<input id="lname" class="form-control" type="text" placeholder="Last Name" required>
</div>
</div> <!-- CLOSE ROW: FULL NAME-->
<div class="form-row">
<button id = "btn" type="submit" class="btn btn-primary">Submit</button>
</div>
</div> <!-- CLOSE CONTAINER -->
</body>
</html>
Here is my javascript code:
<script>
document.getElementById("btn").addEventListener("click",submitBtn);
function submitBtn(){
var myInfo={};
myInfo.profile = document.getElementById("rnum").value;
myInfo.firstName = document.getElementById("fname").value;
myInfo.midName = document.getElementById("mname").value;
myInfo.lastName = document.getElementById("lname").value;
google.script.run.addInfo(myInfo);
document.getElementById("rnum").value = "";
document.getElementById("fname").value = "";
document.getElementById("mname").value = "";
document.getElementById("lname").value = "";
}
</script>
Here is my google script code:
function addInfo(myInfo){
const ss = SpreadsheetApp.openByUrl(url);
const ws = ss.getSheetByName("User_Info");
const imgFolder = DriveApp.getFoldersByName("User Image").next();
const imgIterator = imgFolder.getFiles();
var imgArr = [];
while(imgIterator.hasNext()){
var imgFile = imgIterator.next();
var imgUrl = imgFile.getName();
imgArr.push(imgUrl);
}
ws.appendRow([
myInfo.profile,
myInfo.firstName,
myInfo.midName,
myInfo.lastName
//Image URL
]);
}
So far, I can just get the filenames of the all the images in my Google Drive folder. I am still searching for ways on how to get the image URL based on profile number. Thank you very much in advance for your help and inputs.
If profile number is the filename of images in the folder of DriveApp.getFoldersByName("User Image").next() and each filename is the unique filename, how about the following modification?
From:
var imgArr = [];
while(imgIterator.hasNext()){
var imgFile = imgIterator.next();
var imgUrl = imgFile.getName();
imgArr.push(imgUrl);
}
ws.appendRow([
myInfo.profile,
myInfo.firstName,
myInfo.midName,
myInfo.lastName
//Image URL
]);
To:
var imgObj = {};
while(imgIterator.hasNext()){
var imgFile = imgIterator.next();
imgObj[imgFile.getName()] = imgFile.getUrl();
}
ws.appendRow([
myInfo.profile,
myInfo.firstName,
myInfo.midName,
myInfo.lastName,
imgObj[myInfo.profile]
]);
In this modification, an object for searching the URL is created and the URL is put using the object.
Note:
In this case, I understood as follows.
profile number is the filename of images.
Each filename is the unique filename.
If above my understanding is not correct, can you provide the detail information of your situation? By this, I would like to modify the script.

Upload a picture in signup with Firebase

I am using Firebase.auth to sign up users on my website.
In order to get more informations from them, I also create a Firestore Document that stores more informations. Here is my code:
HTML
<div class="col-md-6">
<div class="row justify-content-center align-items-center h-md-100vh">
<div class="col-10 my-5 my-md-0">
<h2 class="h4 font-weight-bold">Signup To Become A Player</h2>
<form id="player-login-form">
<div class="form-group">
<input type="text" id="player-signup-firstname" name="player_signup[firstname]" required="required" placeholder="What's your firstname?" class="form-control">
<div class="invalid-feedback mt-0"></div>
</div>
<div class="form-group">
<input type="text" id="player-signup-lastname" name="player_signup[lastname]" required="required" placeholder="What's your lastname" class="form-control">
<div class="invalid-feedback mt-0"></div>
</div>
<div class="form-group">
<input type="email" id="player-login-email" name="player_signup[email]" required="required" placeholder="What's your email?" class="form-control">
<div class="invalid-feedback mt-0"></div>
<small id="emailHelp" class="form-text text-muted"></small>
</div>
<div class="form-group ">
<input type="password" id="player-login-password" name="player_signup[password]" required="required" placeholder="Set a password" class="form-control">
<div class="invalid-feedback mt-0"></div>
</div>
<div class="form-group ">
<input type="file" accept="image/*" capture="camera" id="cameraInput">
</div>
<button type="submit" class="btn btn-primary" id="player-signup-button">Create account</button>
</form>
</div>
</div>
</div>
And JS
// The sign up variables and constants
const signUpBtn = document.querySelector('#player-signup-button');
// Sign up function
signUpBtn.addEventListener("click", (e) => {
e.preventDefault(); // avoid the page to refresh when we click signup
// get user info from the id of the input
const loginForm = document.querySelector('#player-login-form');
const firstname = loginForm['player-signup-firstname'].value;
const lastname = loginForm['player-signup-lastname'].value;
const email = loginForm['player-login-email'].value;
const password = loginForm['player-login-password'].value;
// Upload picture part
var refname = 'photos/' + firstname + lastname;
let storageRef = firebase.storage().ref(refname);
let fileUpload = document.getElementById("cameraInput")
fileUpload.addEventListener('change', function(evt) {
console.log("Is code going here?");
let firstFile = evt.target.files[0] // upload the first file only
let uploadTask = storageRef.put(firstFile).then(function(fileSnapshot) {
firebase.firestore().collection('players').add({
firstname: firstname,
lastname: lastname,
email: email,
profilepic: fileSnapshot.ref.getDownloadURL()
});
})
});
auth.createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
M.toast({html:error.message});
}).then( cred => {
loginForm.reset();
});
});
**My question: ** I have issues for the image uploading part. It looks like the code inside fileUpload.addEventListener is not read by the interpreter.
Do you have any ideas where is the issue?
You need to put this callback registration outside the click handler:
document.getElementById("cameraInput").addEventListener('change', function(evt) {...});
Right now your code says "after the user submits the form, start listening for them to browse for a picture" when what you really want is "when the page loads, start listening for the user to browse for a picture. Afterwards, when they submit the form read the selected picture file and send it to the server."

Upload and Display Images using HTML, JS and MONGODB

I have managed to load the image on my page using HTML and JS but I can't seem to post the image to my MongoDB and it won't show on my 'home' page.
HTML:
<div class="container">
<h1 style="text-align: center">Post a New Guitar</h1>
<div class="col-md-6">
<form action="/guitars" method="POST">
<div class="input-group">
<label>Item Name</label>
<div class="input-group">
<input class="form-control" type="text" name="name" placeholder="Name">
</div>
<label>Upload Image</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" id="imgInp">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<img id="img-upload"/>
<div class="input-group">
<button class="btn btn-lg btn-primary btn-block">Submit!</button>
</div>
Go Back
</div>
JS:
$(document).ready( function() {
$(document).on('change', '.btn-file :file', function() {
var input = $(this),
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [label]);
});
$('.btn-file :file').on('fileselect', function(event, label) {
var input = $(this).parents('.input-group').find(':text'),
log = label;
if( input.length ) {
input.val(log);
} else {
if( log ) alert(log);
}
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-upload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
});
When submitting the form, I want it to display the image that has been uploaded using JS and for it to be 'saved' to my database.
What do you mean by "post the image to MongoDB"? You shouldn't be saving image in the database.
What you want to do is when you upload in image, store it in a publicly accessible location in your server. What you save in the database is not the image itself but the location of the image on the server.
Image stored in the server:
/home/public/image.jpg
Image path stored in Mongo DB:
{
path: '/home/public/image.jpg'
}
When you go back to your html page, you just need to query the path of the image in Mongo DB and use that value as a source in your image tag.
`<img src="${path}" />`

Categories