How to add img src attribute with VueJs - node.js

In my NodeJs route, I have the following:
router.get('/list/:id', function(req, res, next) {
request("http://localhost:3000/api/journal/" + req.params.id, function(error, response, body) {
var json = JSON.parse(body);
res.render('listdetail', { title: 'Journal', data: json });
});
});
The data is a json object containing all my screen fields. One of the fields is a base64 presentation of an image.
Then, in my List Detail html I have the following:
<div id="app">
<img class="materialboxed" src="{{data.base64Image}}" width="200">
</div>
This is surely not working... How can I add to the src attribute the base64 information that was sent by NodeJS?
I tried also the following:
<img class="materialboxed" :src=imagebase64Source width="200">
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
imagebase64Source: {{data.base64Image}}
}
})
</script>
But it obviously does not work
Thanks
EDIT:
Strange, it's working now!
Here's what I've done:
<img class="materialboxed" src="{{ data.base64Image }}" width="200">
The only difference I can see is the spacing between the mustache.
Thanks to all who helped.

You can do it simply like this:
<template>
<div>
<img :src="image"/>
</div>
</template>
<script>
module.exports = {
data: function() {
return {
image: //your b64 string there
};
}
};
</script>
Pay attention by the way, depending on what you have on your string, you may have to add a header to the raw string.
<template>
<div>
<img :src="imgWithHeader"/>
</div>
</template>
<script>
module.exports = {
data: function() {
return {
image: //your b64 string there
};
},
computed: {
imgWithHeader() {
return 'data:' + MIMETypeOfTheImage + ';base64,' + this.image;
}
}
};
</script>
Of course you should figure out what is the type of the image, in this case.

I think the method you tried should work if the syntax is corrected
So this:
<img class="materialboxed" :src=imagebase64Source width="200">
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
imagebase64Source: {{data.base64Image}}
}
})
</script>
should be changed to this:
<img class="materialboxed" :src="imagebase64Source" width="200">
<script type="text/javascript">
var app = new Vue({
el: '#app',
data () {
return {
imagebase64Source: data.base64Image,
}
}
})
</script>

Related

Vue pass parameter using handlebars

Hello i use nodejs with express and handlebars and vue 2.6
I want pass {{audioannotationid}} to my vue component but i can't,
what are i'm doing wrong?
sorry for my english
This my edit.hbs
<div> Editar audio annnotations</div>
<div id="EditAudioannotations" idParametro="beowulfdgo" >
</div>
{{audioannotationid}}
This my component
<template>
<div id="EditAudioannotations" >Hola {{who}}
{{valor}}
</div>
</template>
<script>
export default {
name: 'EditAudioannotations',
props:{idParametro:{
type: String,
default: '0',
},},
data() {
return {
who:"world",
json: {},
valor:"otro valor"
};
},
methods: {
},
beforeMount() {
},
};
</script>
<style></style>
This my index.js
if(window.location.pathname.match(/\/audioannotations\/edit\//)){
// window.Vue = Vue
Vue.use(VueAxios, axios);
Vue.component("EditAudioannotations", EditAudioannotations);
window.vm = new Vue({
el: '#EditAudioannotations',
render: h => h(EditAudioannotations)
})
}
This muy result
I resolved obtain id from url becase i don't use routex, in vue add this method
created() {
var currentUrl = window.location.pathname;
this.ruta=currentUrl
//console.log(currentUrl);
var ultimoSlash = this.ruta.lastIndexOf("/");
this.ruta=this.ruta.substring(ultimoSlash+1)
},

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

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

knockout textbox validation error

i am facing problem with knockout basic textbox validation
Here is my html
<input type="text" data-bind="value:text" />
<br />
<br />
<input type="button" data-bind="click:save" value="save" />
Here is my script
$(document).ready(function () {
ko.validation.registerExtenders();
ko.validation.configure({
registerExtenders: true,
decorateElement: true
});
var vm = ko.validatedObservable({
text: ko.observable().extend({
required: true
}),
save: function () {
debugger;
if (this.isValid()) {
alert('success');
}
else {
this.errors.showAllMessages();
alert('error');
}
}
});
ko.applyBindings(vm);
});
I have included below scripts
<script src="/Scripts/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="/Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="/Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script src="/Scripts/knockout.validation.min.js" type="text/javascript"></script>
when i run this i am getting 'Undefined is not a function' at "this.isValid()"
Please help me.
I prefer this pattern to use validatedObservable - http://codepen.io/dmoojunk/pen/PwNbEL
ko.validation.registerExtenders();
ko.validation.configure({
registerExtenders: true,
decorateElement: true
});
var vm = function(){
var self = this;
self.text= ko.observable().extend({
required: true
}),
self.save= function () {
if (this.isValid()) {
alert('success');
}
else {
this.errors.showAllMessages();
alert('error');
}
}
};
var viewmodel = ko.validatedObservable(new vm())();
ko.applyBindings(viewmodel);

How to: Use ejs without express

I'm starting with node in general, and I'm attempting to do a site without express.
I would none the less want to use ejs to inject my html and this is where my problem is...
How do I attach the ejs.render(...) to the response?
PS: I know it might be a better option to use express, but I want to know how it works underneath before bridging it.
Something like:
var ejs = require("ejs");
function index (response, request, sequelize) {
response.writeHead(200, {"Content-Type": "text/html"});
test_data = "test data";
response.end(ejs.render("./views/home.html",test_data));
}
exports.index = index;
But that works ^_^
Thanks!
First of all, You need install ejs -> $ npm install ejs --save
Simple example:
main.ejs:
<p> <%= exampleRenderEjs %> </p>
server.ejs
var ejs = require('ejs');
var fs = require('fs');
var htmlContent = fs.readFileSync(__dirname + '/main.ejs', 'utf8');
var htmlRenderized = ejs.render(htmlContent, {filename: 'main.ejs', exampleRenderEjs: 'Hello World!'});
console.log(htmlRenderized);
There is a project called Consolidate.js which provides a common API for many template engines. This ensures they can all be interchangeable. If you want to render templates directly, you want to be compatible with this API.
Sample code from the Consolidate.js README:
var cons = require('consolidate');
cons.swig('views/page.html', { user: 'tobi' }, function(err, html){
if (err) throw err;
console.log(html); // Or write to your `res` object here
});
This sample is for Swig, but similar code works for EJS or any of the compatible engines.
Example from some book:
template.ejs
<html>
<head>
<style type="text/css">
.entry_title { font-weight: bold; }
.entry_date { font-style: italic; }
.entry_body { margin-bottom: 1em; }
</style>
</head>
<body>
<% entries.map(entry => { %>
<div class="entry_title"><%= entry.title %></div>
<div class="entry_date"><%= entry.date %></div>
<div class="entry_body"><%= entry.body %></div>
<% }); %>
</body>
</html>
function blogPage(entries) {
const values = { entries };
const template = fs.readFileSync('./template.ejs', 'utf8');
return ejs.render(template, values);
}
const server = http.createServer((req, res) => {
const entries = getEntries();
const output = blogPage(entries);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(output);
console.log('run server');
});
server.listen(8000);

Resources