In here, I want to preview image before update profile picture - node.js

Before updating profile picture, I want to preview it. So, here I use function to preview and submit it. But, this two of task can't be do in one fuction. If you know how to do it. Please help me.
<div class="mb-3">
<label for="formFile" class="form-label">
{" "}
<strong> Profile Picture</strong>{" "}
</label>
<div className="row">
<div className="col-sm-4">
<img className="img shadow" src={file} alt="select image" />
</div>
<div className="col-sm-8">
<input
class="form-control"
type="file"
id="file"
filename="file"
onChange={onChangeFile}
required
/>
</div>
</div>
</div>
this is the function i used
const onChangeFile = (e) => {
setfile(e.target.files[0]);
const [file] = e.target.files;
setfile(URL.createObjectURL(file));
// if (e.target.files && e.target.files[0]) {
// setfile(URL.createObjectURL(e.target.files[0]));
// setfile(e.target.files[0]);
// }
};

https://jakub-kozak.medium.com/how-to-open-the-native-camera-in-mobile-browsers-327820fa669a
This article explains how to do preview a photo you have uploaded / taken!

Related

Cannot read property 'heading' of null

My problem is I got an unexpected error at the browser end that says Cannot read property 'heading' of null
also marks this error at the client page file like about.ejs and showing; in the snap attached
I have provided all the required codes related to this. I reviewed multiple times to find for what or to where the actual errror originated but did not able to fix it.
codes of about.ejs
<%-include('./partials/header')%>
<div class="container-fluid">
<h1>About Section</h1>
<div class="card shadow mb-4">
<div class="card-header">
<form action="/admin/portfolio/create" method="post">
<button type="submit" class="btn btn-success">Edit About Page</button>
</form>
</div>
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">About Area</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<form action="/admin/about" method="post" >
<div class="form-group">
<label for="exampleFormControlInput1">Headings:</label>
<input class="form-control" type="text" name="heading" id="exampleFormControlInput1" value="<%=about.heading%>" >
</div>
<div class="form-group">
<label for="exampleFormControlInput2">Sub-Headings:</label>
<input class="form-control" type="text" name="subheading" id="exampleFormControlInput2" value="<%=about.subheading%>" >
</div>
<div class="form-group">
<textarea id="editor1" name="content" rows="10" cols="80"><%=about.content%></textarea>
</div>
<button type="submit" class="btn btn-primary">Save & Update</button>
</form>
</div>
</div>
</div>
<%-include('./partials/footer')%>
here is my router.js file
router.get('/admin/about',serverController.isAuthenticated,serverController.about)
router.post('/admin/about',serverController.isAuthenticated,serverController.about_post)
This is also my controller file
exports.about = async function(req,res){
res.render('server/about', {
about : await aboutCollection.findOne()
})
}
exports.about_post = function(req,res){
let about = new About(req.body)
about.create().then(async()=>{
res.redirect('/admin/about')
}).catch(()=>{
res.send('404')
})
}
and finally this all about my model of about page
const aboutCollection = require('../db').db().collection('about')
const objectId = require('mongodb').ObjectID
const About = function(about){
this.about = about
}
About.prototype.create = function(){
return new Promise(async(resolve,reject)=>{
await aboutCollection.updateOne({}, {$set :
{
heading : this.about.heading,
subheading : this.about.subheading,
content : this.about.content
}
})
resolve()
})
}
module.exports = About
it's because about sent value of none at the ejs tag i mean
<%= about.heading%>
Do,
exports.about = async function(req,res){
res.render('server/about', {
about : await aboutCollection.find().toArray()
})
}
Instead of,
exports.about = async function(req,res){
res.render('server/about', {
about : await aboutCollection.findOne()
})
}
In my case, I did this; after trying then see error has gone.

Cannot POST /admin Error return in web browser

I want to update my images on the blog page. but I got an error in the web browser like
Cannot POST /admin/portfolio/609911b1fba77be609396747/edit_cover
here is edit_cover.ejs file code and I use post method to submit images in the database
<%-include('./partials/header')%>
<div class="container-fluid">
<h1 class="text text-primary">Change Porfolio Cover Image Section</h1>
<div class="card shadow mb-4">
<div class="card-header">
<form action="/admin/portfolio/<%=work._id%>/edit_cover" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleFormControlFile1">Cover</label>
<input type="file" name="cover" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile2">Snaps of Project</label>
<input class="form-control-file" name="images" type="file" id="exampleFormControlFile2" multiple>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" >Update</button>
</div>
</form>
</div>
<div class="card-body">
<div class="table-responsive">
</div>
</div>
</div>
My router.js file code is here and two lines of code in here one is get request and other is for post
router.get('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
here is my backend controller and code for images updating
exports.portfolio_edit_cover = async function(req,res){
res.render('server/edit_cover',{
work : await workCollection.findOne({_id: objectId(req.params.id)})
})
}
exports.portfolio_edit_cover_post = function(req,res){
let uploadImages = new Work(req.body, req.files, req.params.id)
console.log(req.files)
uploadImages.up().then((result)=>{
res.redirect('/admin/portfolio',{
work : result
})
}).catch(()=>{
res.send('404')
})
}
and lastly this all about my model codes. in the following code is just for how update my data onto databae
Work.prototype.up = function(){
return new Promise(async(resolve,reject)=>{
await workCollection.updateOne({_id : objectId(this.id)}, {$set :
{
images : this.images
}
}
)
resolve()
})
}
module.exports = Work
in edit_cover.js file it has path like
action="/admin/portfolio/<%=work._id%>**/edit_cover**" and router.js it's like
router.get('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
both of these need to have the same path; everything is fine but at last segment, it should be /cover_edit

Not able to update and delete data from mongoose

I am using ejs template, expressjs, and mongoose. not able to update existed data through form while click on edit button and as well not able to delete it . I want to delete when user click a button as well when user click on edit button it show form and allow him to edit. I already wrote get route , it is working fine.
**Update route:**
router.put('/success123' , function (req, res) {
// const id = req.params.id;
Campaign.findById(id)
.then(campaign => {
campaign.Title = req.body.title;
campaign.Description = req.body.Description;
campaign.save().then(updatePost => {
res.render('success123');
});
});
});
**Delete route**
router.delete ('/delete/:id' , function (req, res){
Campaign.findByIdAndDelete(req.params.id)
.then(deletedPost => {
res.render('success');
});
});
I am getting error and cant figure it out . Event it is not showing any error message in my console. both deleting and updating parts not working and i am able to success fully get route while user click on edit campaign button.
My ejs template for update : THIS IS MY EJS TEMPALTE WHERE I AM SENDING UPDATE INFORMATION THROUGH FORM
<div class="row p-4">
<div class="col-md-7">
<form action="/success123" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" value="<%=camplist.Title%>" class="form-control" name="title" id="title" placeholder="Enter The Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea value="" name="description" id="description" class="form-control" placeholder="Enter your content here" rows="10"><%=camplist.Description%></textarea>
</div>
<div>
<input class="form-control" name="rules" type="hidden" placeholder="Enter The Title">
<textarea name="rules" id="editor"></textarea>
</textarea>
</div>
<div class="form-group">
<label for="file">Upload Your Banner Image </label>
<input type="file" class="form-control" id="file" name="uploadedFile" accept="image/jpeg, image/jpg, image/png, image/bmp">
</div>
<button class="btn btn-outline-success btn-lg" type="submit">Update Post</button>
</form>
I am getting error and cant figure it out . Event it is not showing any error message in my console. both deleting and updating parts not working and i am able to success fully get route while user click on edit campaign button.

Uploading file to EC2 Web Server from Web Application

I am creating a simple application using Sails.js. What it basically does is it creates a new Item then saves it to the database and uploads the image to S3.
Here's what happens:
When I run my application on my local, it behaves okay. The req.body has contents, and the req.file('item-image') is not empty.
I am running it on EC2 now, and the problem is, the req.body is just an empty object, but the req.file('item-image') is not empty. I've tried different debugging scenarios, see them below:
If I remove the enctype="multipart/form-data" (I know this is needed for file upload, just trying), I get the req.body object that I expect, but as expected, the req.file('item-image') is empty.
I put back the enctype="multipart/form-data" then tried sending the request without the file, I get my expected req.body object.
I included an image on my request, the req.body object is empty, but the req.file('item-image') isn't.
The weirdest part is, when I send my request through postman, all behaves as expected. I'm really lost now, see my code below:
create_event.ejs
<form action=<%= event.createUrl %> method="POST" id="form-item" enctype="multipart/form-data">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="blue bigger">Please fill the following form fields</h4>
</div>
<div class="modal-body overflow-visible">
<div class="row">
<div class="col-xs-12 col-sm-5">
<div class="space"></div>
<input type="file" name="item-image"/>
</div>
<div class="col-xs-12 col-sm-7">
<div class="form-group">
<label for="form-field-username">Name</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Name" name="item-name" />
</div>
</div>
<div class="space-4"></div>
<div class="form-group">
<label for="form-field-username">Description</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Description" name="item-description"/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-sm" data-dismiss="modal">
<i class="icon-remove"></i>
Cancel
</button>
<button class="btn btn-sm btn-primary" id="save-item">
<i class="icon-ok"></i>
Save
</button>
</div>
</div>
</div>
</form>
create_event.js
$('#save-item').on('click', function(e){
var response = confirm('Are you sure you want to continue saving this item?');
if(response == true) {
$('#form-item').submit();
}
});
AdminController.js
createItem: function(req, res){
console.log('Saving..');
console.log(req.body);
var eventId = req.path.split('/')[4];
req.file('item-image').upload(function callback(error, uploadedFile){
if(error) {
console.log(error);
return res.serverError();
}
console.log(uploadedFile);
s3Helper.upload(uploadedFile[0], function(error, data){
if(error) {
return res.serverError();
}
var item = {
ITEM_ID: uuid.v1(),
EVENT_ID: req.path.split('/')[4],
NAME: req.body['item-name'],
DESCRIPTION: req.body['item-description'],
IMAGE_URL: data.Location
}
EventItem.create(item, function(error, data){
if(error) {
console.log(error);
return res.serverError();
}
console.log('Successfully saved data: ');
console.log(data);
return res.redirect('/admin/events/' + eventId);
});
});
});
},
Thank you!
I found the answer here https://github.com/balderdashy/sails/issues/2508
Apparently, sails.js uses skipper and is sensitive on the order of the input. I just put the file part on the end and it now works.
I'm just confused as to why it works on my local, and not on my ec2 server.

Parsing nested data from select form with Angularjs

I'm trying to parse a model from a form which contain a select(ngOptions) and save it to db but the selected value is never parsed. i'm stuck here can someone help please.
here is my code:
View
<section class="container" data-ng-controller="TagsController" >
<h2><i class="fa fa-pencil-square-o"></i>Add a new Tag</h2>
<form class="form-horizontal col-md-5" data-ng-submit="create()">
<div class="form-group ">
<div class="controls">
<input type="text" class="form-control input-lg" data-ng-model="label" id="label" placeholder="Label" required>
</div>
</div>
<div class="form-group" data-ng-controller="CategoriesController" data-ng-init="find()">
<select class="form-control input-lg" ng-model="category._id" ng-options="category._id as category.label for category in categories">
<option value="">Choose a Category</option>
</select>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn">
</div>
</div>
</form>
</section>
controller
angular.module('mean.tags').controller('TagsController', ['$scope', '$routeParams', '$location', 'Global', 'Tags', function ($scope, $routeParams, $location, Global, Tags) {
$scope.global = Global;
$scope.create = function() {
var tag = new Tags({
label: this.label,
category: this.category
});
tag.$save(function(response) {
$location.path("tags/");
});
this.label = "";
this.category = "";
};
...
I found the problem so i will answer my question. The problem was due to architecture restrictions, Angularjs don't allow to nest a ng-controller inside an other one...

Resources