Croppie and NodeJS : Upload resized images - node.js

I'm trying to upload squared images for my ecommerce app.
I want all my images to be square for products images.
I'm using croppie Js, Expressjs and ejs.
Here is my actual code :
<label>Image</label>
<div id="modal">
<a class="button actionUpload">
<input class="from-control" type="file" id="upload" value="Choose Image" name="image" accept="image/*">
</div>
</a>
<div id="main-cropper"></div>
<button class="actionDone">Done</button>
And my JavaScript
var basic = $('#main-cropper').croppie({
viewport: {
width: 200,
height: 200
},
boundary: {
width: 300,
height: 300
},
showZoomer: true,
url: '/images/logo_AR.png'
});
basic.hide()
function readFile(input) {
if (input.files && input.files[0]) {
basic.show()
var reader = new FileReader();
reader.onload = function (e) {
$('#main-cropper').croppie('bind', {
url: e.target.result
});
$('.actionDone').toggle();
$('.actionUpload').toggle();
}
reader.readAsDataURL(input.files[0]);
}
}
$('.actionUpload input').on('change', function () {
readFile(this);
});
$('.actionDone').on('click', function () {
$('.actionDone').toggle();
$('.actionUpload').toggle();
})
When I upload the image on AWS using multer on my rooter, the crop doesnt work and the images isn't modified...

Related

How do i auto-refresh my log rather then refreshing it manually

I currently have a log box which shows the log from my backend. I have a button to refresh the log and the latest set of logs shows up. How do I set it to a auto-refresh log?
I have the code below for the button and switchbox
<div class="form-group row m-b-10">
<label class="col-form-label">Auto-Refresh:</label>
<div class="col-md">
<div class="switcher switcher-success">
<input type="checkbox" v-model="checked" name="switcher_checkbox_2" id="switcher_checkbox_2" checked="true" value="1" v-on:change="toggle">
<label for="switcher_checkbox_2"></label>
</div>
<div class="switcher switcher-success">
<button v-if="!checked" #click="logNode(namespace)" class="btn btn-xs btn-success">Refresh</button>
</div>
</div>
And the function for the refresh button is below. How do I call a function for the log to load on auto refresh when the switchbox is on?
logNode(namespace) {
console.log(namespace)
this.hidemodal = true;
this.logShow = true;
var requestobj = {
Namespace: namespace,
};
var apiobj = {
tablename: "bnm",
Id: VueCookies.get("activeNetwork_Id"),
method: "post"
};
var obj = {
apiobj: apiobj,
mainobj: requestobj
};
this.$store
.dispatch("logsAPI", obj)
.then(response => {
console.log(response);
console.log("test result");
if (response.data || response.status == 200) {
this.logString = response.data.Logstr;
this.$notify({
group: "querynotify",
title: "Success",
type: "success",
position: "top-right",
text: "Sucessfully Created Logs " + ":\n" + response.data.Username
});
} else {
this.$notify({
group: "querynotify",
title: "Error",
type: "warn",
position: "top-right",
text: "Error Creating Logs " + ":\n" + response.data.Username
});
}
})
.catch(error => {
this.$notify({
group: "querynotify",
title: "Error",
type: "error",
position: "top-right",
text: "Error View this node Log" +
":\n" +
error.data.err +
":\n" +
error.data.details
});
});
},
When you check box is checked, you can use setInterval() and when your checkbox is unchecked clearInterval.
Please check below working snippet.
*Note in this snippet, I have just used simple log for demo purpose. In that demo you can put your logic.
new Vue({
el: '#app',
data: {
checked: false,
autoRef:null
},
methods: {
toggle() {
if(this.checked){
this.autoRef = setInterval(() => {
this.logNode('Auto refresh called');
}, 3000);
}else{
clearInterval(this.autoRef);
}
},
logNode(msg) {
console.log(msg)
}
}
});
.btn-success {
background: green;
padding: 10px;
border: 1px solid #ccc;
color: #fff;
}
<link href="https://cdn.jsdelivr.net/npm/vuetify#1.2.2/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify#1.2.2/dist/vuetify.min.js"></script>
<div id="app" class="form-group row m-b-10">
<label class="col-form-label">Auto-Refresh:</label>
<div class="col-md">
<div class="switcher switcher-success">
<input type="checkbox" v-model="checked" name="switcher_checkbox_2" id="switcher_checkbox_2" checked="true" value="1" v-on:change="toggle">
<label for="switcher_checkbox_2"></label>
</div>
<div v-if="!checked" class="switcher switcher-success">
<button ref="myButton" #click="logNode('on button click')" class="btn btn-xs btn-success">Refresh</button>
</div>
</div>

PayloadTooLargeError: request entity too large when upload image

I am trying to upload/and save an image in base64 format to my mongo database.
If I use a very very small image it works, but I try to use an image of 161 kb, I have this error:
PayloadTooLargeError: request entity too large
So I try to convert my image with Json but I got an error or it doesn't work,
Her my code ( I am using vue):
<template>
<div class="profile">
<div class="px-4">
<div class="row justify-content-center">
<div class="col-lg-3 order-lg-2">
<div class="card-profile-image image-preview">
<div v-if="profImage !=undefined && profImage.length > 0">
<a>
<img
:src="profImage"
class="rounded-circle"
/>
</a>
</div>
<div>
<div class="file-upload-form">
Upload image:
<input
type="file"
#change="previewImage"
accept="image/*"
/>
</div>
<div class="image-preview" v-if="imageData.length > 0">
<img class="preview" :src="imageData" />
<button #click="updateUserImage"></button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
Here my js file:
<script>
import DataService from '#/services/DataService'
export default {
name: 'Profile',
data: function() {
return {
username: '',
imageData: '',
profImage: '',
}
},
methods: {
previewImage: function(event) {
var input = event.target
if (input.files && input.files[0]) {
var reader = new FileReader()
reader.onload = e => {
this.imageData = e.target.result
}
reader.readAsDataURL(input.files[0])
}
},
async getAllInfo() {
var userImage = await DataService.getUserImage({
username: this.username
})
this.profImage = userInfo.data.user[0].profImage //IT Works
this.profImage = JSON.parse(userInfo.data.user[0].profImage) //I get an error
},
async updateUserImage() {
var temp = JSON.stringify(this.imageData)
console.log(this.firstname)
await DataService.updateUserInfo({
username: this.username,
user: {
profImage: temp
}
})
}
},
mounted() {}
}
</script>
When I try to use "JSON.parse(userInfo.data.user[0].profImage)"I get an error :
"Unexpected token d in JSON at position 0"
I also try with JSON.Stringify, but I get is not a function.
In my db, the image is saved in this way:
profImage: {
image: Buffer,
require: false
},
What am I doing wrong? I am using mongodb, vue , express and node.
I change the parser limit using
bodyParser.json({ limit: "50mb" })
and works for me

Save file to mongodb using angular and Nodejs

I am trying to upload an image to mongodb using angular and nodejs. The code is below. I got the backend working but the problem is with the html input i get 'C:fakepath/file.xyz'. I was looking online and saw that there is not a way to get the relative path of the file. Can someone please tell me how i can change my front end code to get and send the file path to the backend to then save. I read that the browser doesnt allow relative path of the file but then how can I upload. Thanks!
The nodejs image save method is:
async function SaveImage(userParam) {
const entry = new imageEntries(userParam);
entry.image.data = fs.readFileSync(userParam.imagePath);
entry.image.contentType = 'image/png';
await entry.save();
}
The html code is:
<div class="upload-btn-wrapper">
<button class="btn">Upload a file</button>
<input type="file" name="myfile" id="myFile" />
</div>
What I pass as the path in the backend is:
ImageJournal.imagePath = (<HTMLInputElement>document.getElementById('myFile')).value;
but with the code above i get the following error:
ENOENT: no such file or directory, open 'C:\fakepath\chapter9problemsandanswers.doc'
Ok here it is:
HTML:
<div class="form-group">
<label for="pdf">PDF</label>
<input type="file" id="pdf" (change)="onFileChange($event)" #fileInput>
<button type="button" class="btn btn-sm btn-default" (click)="clearFile()">clear file</button>
</div>
TS:
import { Component, OnInit, ElementRef, ViewChild } from '#angular/core';
#ViewChild('fileInput') fileInput: ElementRef;
public image;
onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
let file = event.target.files[0];
reader.readAsDataURL(file);
let value = <String>reader.result;
reader.onload = () => {
this.image = {
filename: file.name,
filetype: file.type,
value: value.split(',')[1]
};
};
}
}
Then send the image with http post with a service.
On the server:
// send file
app.post('/api/sendFile', function (req, res) {
File.create({
filename: req.body.filename,
filetype: req.body.filetype,
value: req.body.value
}, function (err, file) {
if (err)
res.send(err);
else {
const response = {
name: file.filename
}
res.send(response);
}
});
});
This is written with mongoDb and mongoose and I have a model named File.
This is all it need to save it.

Fetch a variable from node_modules

I am trying to fetch a variable from node_modules to my application. I have exported it with module.exports, but when I use require('path/of/required/file/in/node_modules') it is showing 'unexpected token import'. I am trying to get the user info from node_modules since there is no official strategy for keystone to fetch the user data.
My local file
var keystone = require('keystone');
Teaching = keystone.list('teaching');
UserInfo = require('../../node_modules/keystone/admin/client/App/components/Footer/index.js').footer;
User = keystone.list(keystone.get('user model'));
console.log(User);
exports = module.exports =function(req,res){
var view = new keystone.View(req,res);
var locals = res.locals;
locals.section = 'teaching';
locals.data = {
teachingData : []
};
view.on('init',function(next){
var teaching = Teaching.model.find();
teaching.exec(function(err,results){
locals.data.teachingData = results;
//console.log(locals.data.teachingData);
next(err);
});
});
view.render('teaching');
}
Node_module file
import React from 'react';
import { css, StyleSheet } from 'aphrodite/no-important';
import { Container } from '../../elemental';
import theme from '../../../theme';
var Footer = React.createClass({
displayName: 'Footer',
propTypes: {
appversion: React.PropTypes.string,
backUrl: React.PropTypes.string,
brand: React.PropTypes.string,
user: React.PropTypes.object,
User: React.PropTypes.object, // eslint-disable-line react/sort-prop-types
version: React.PropTypes.string,
},
// Render the user
renderUser () {
const { User, user } = this.props;
if (!user) return null;
return (
<span>
<span> Signed in as </span>
<a href={`${Keystone.adminPath}/${User.path}/${user.id}`} tabIndex="-1" className={css(classes.link)}>
{user.name}
</a>
<span>.</span>
</span>
);
},
render () {
const { backUrl, brand, appversion, version } = this.props;
return (
<footer className={css(classes.footer)} data-keystone-footer>
<Container>
<a
href={backUrl}
tabIndex="-1"
className={css(classes.link)}
>
{brand + (appversion ? (' ' + appversion) : '')}
</a>
<span> powered by </span>
<a
href=""
target="_blank"
className={css(classes.link)}
tabIndex="-1"
>
VK
</a>
<span> version {version}.</span>
{this.renderUser()}
</Container>
</footer>
);
},
});
/* eslint quote-props: ["error", "as-needed"] */
const linkHoverAndFocus = {
color: theme.color.gray60,
outline: 'none',
};
const classes = StyleSheet.create({
footer: {
boxShadow: '0 -1px 0 rgba(0, 0, 0, 0.1)',
color: theme.color.gray40,
fontSize: theme.font.size.small,
paddingBottom: 30,
paddingTop: 40,
textAlign: 'center',
},
link: {
color: theme.color.gray60,
':hover': linkHoverAndFocus,
':focus': linkHoverAndFocus,
},
});
exports.footer = Footer.renderUser();
1) The "Unexpected token import" error is probably occuring because the current JavaScript environment does not support the import statement; the code you are trying to import from the Keystone node module is transpiled before it gets used normally. When Keystone uses that component, it's not an issue. But if you're importing a React component into a non-React file, you're bound to have problems. Which leads to my next question:
2) UserInfo isn't used in your code at all. You can't just use Keystone's React component for showing user information, unless you are working in a React environment (which it does not look like you are.) What is your use case for using this component?

How to send a large datauri of an image to express server

I have the daturi of an image which is uploaded from the desktop.I would like to send this data uri to express server so as to save the dataUri in a text file. Since the size of the data uri of the image is quite large I am getting payload too large error which is understandable. I tried using multer but I couldn't figure out how to extract the data uri of the image when multer is used, on the server side.Any help on this is greatly appreciated.
Below is some of the code sample that I am trying to use
<div class="row">
<div class="form-group">
<label class="btn btn-default btn-file" for="FileUpload">Upload a Plan</label>
<input type="file" id ="FileUpload" accept="image/*" capture="camera" value="" onchange="readFileURL(this);" style="display: none;">
<img id="chosenFile" src="#" style="visibility: hidden;"/>
</div>
</div>
<div class="row">
<div class="col-sm-12"><button style="background-color: green" class="btn btn-default btn-sm" onclick="handleUplod(this)">Upload</button></div>
</div>
<script type="text/javascript">
function readFileURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
document.getElementById("chosenFile").style.visibility="visible";
reader.onload = function (e) {
$('#chosenFile').attr('src', e.target.result).width(150).height(150);
console.log("result:",e.target.result);
imageData = e.target.result;
};
console.log("data url:"+reader.readAsDataURL(input.files[0]));
}
};
function handleUplod(){
$.ajax({
type: "POST",
url: "/send",
data: { MyPlanDataUri:imageData },
success: function(result){
location.href= "/someplace";
},
error: function(result) {
alert('error');
}
});
};
On the server side I am doing the following
app.post('/send', function(req,res) {
var Tex1 = req.body.MyPlanDataUri;
var newFile = "ImageFile.txt";
fs.writeFile(newFile, Tex1, (err) => {
if (err) res.send(err);
console.log('File saved successfully ! - ', newFile);
}
);
res.send("Successfull");
}
P.S the above code works perfectly fine for small datauri's

Resources