Convert <img src="phone.png"> to Base64 <img src="data:img/png;base64,...."> by compiling the app, to make the image load instantly with the app - node.js

This is a unique question: I don't want to use browser javascript to solve this, please read on...
I want to convert <img src="..."> to Base64 img tag by compiling the app (ng build or ng serve), to make the image load instantly - without further downloads other than the app itself, but also to make the image dynamicly changable while developing the app.
For example, here's a component - home.component.html:
code before compiling (notice the base64 directive, its just an idea though):
<img src="assets/images/phone.png" base64>
code wanted after compiling:
<img src="data:image/png;base64,iVBORw0......rest-of-base-64-goes-here">
Important: This should happen without running a front-end javascript operation by the user, or by calling the image file. (by means, the file phone.png will not even exist when compiling)
I still want to edit the local image phone.png while developing.
I know I can convert the file to base64 manually and update it in my component, but that's exactly what I don't want to do - I want it to happen automatically to save time.
That means the image will sit in the component itself, in one of the .js files that has been compiled, and therefore will load instantly with the app.
Idea: It would be nice and easy to have a directive that would take care of that.
something like <img src="phone.png base64>**
I assume it can be done using node/webpack in some way, but I have not idea how.

You need to use readAsDataUrl()
function getBase64(event) {
let me = this;
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
//me.modelvalue = reader.result;
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
Hope can help you..

Related

Get image from server side folder and display image in Vue

I'm trying to display image from public folder of my node api directory. I want to display image in front end vue file. I don't know how to give source of image.
This is the directory. I want to display image nodelogin.png
I want to display these images.
<img :src="myimage" alt="Logo" width="80" height="80" />
This is my template code.
async created() {
this.myimage = await this.getImage();
},
methods: {
async getImage(){
return await 'http://localhost:4000/api/public/nodelogin.png';
}
}
But this code gives an error response.
Cannot GET /api/public/nodelogin.png
Actually I'm new to node and Vue So I'm not sure whether my logic is correct or not.
Do I need to do something from my backend side?
Just use the url '/nodelogin.png'
Thanks for your question posting.
If you want see png, you should input url :
http://localhost:4000/nodelogin.png
Good luck for your business.

Phaser problem: loading images imported from files as base64 data

I have trouble loading image(s) as Base64 data. In the following code (partially borrowed from here), the 'loading' function this.textures.addBase64 is used:
import bgSrc from '../assets/img/back.png';
...
create() {
this.numToLoad = 1;
this.textures.on('addtexture', () => {
console.log('another image loaded')
this.numToLoad--;
if (this.numToLoad < 1) this.createNext();
})
this.textures.addBase64('background', bgSrc);
...
}
createNext() {
//...use the images
}
However, the 'addtexture' event never fires. And the image, loaded this way, never loads, no matter how long I wait.
But everything goes fine if I use direct Base64 code, like const bgSrc = 'data:image/png;base64, blablablah' instead of import bgSrc from '../assets/img/back.png'. So the problem is in importing the image.
I use phaser 3 webpack in this project. plus url-loader. Maybe the url-loader is incorrectly set up? I am not sure if the url-loader is even needed for performing npm run start.
Well, it was indeed an incorrect setup of the url-loader. (I used one more plugin in the webpack, and they didn't work well together.)
So, the code above is OK after all.

How to upload a file using WebdriverIO

I'm trying to port the following code from Ruby with the selenium-webdriver gem to Node.js with WebdriverIO:
#webdriver.navigate.to "https://imgur.com/upload"
element = #webdriver.find_element(:id, 'global-files-button')
element.send_keys("C:\\test\\image.png")
As you can see the code is very simple: navigate to a url, find the input, set the file path and it works as expected selecting the file for upload.
This is my ported version:
describe('User can upload', () => {
it('select file', () => {
browser.url("https://imgur.com/upload");
browser.waitForExist('#global-files-button');
$('#global-files-button').keys("C : \\ t e s t \\ i m a g e . p n g".split(" "));
});
});
Unfortunately this test doesn't set the path and I haven't been able to find a working example of uploading a file like this with wdio and the documentation has left me guessing. Any suggestions much appreciated.
I'm aware of both chooseFile and uploadFile but I'm working with a cloud platform to run my wdio tests and they don't seem to work reliably.
I've had trouble with this. From what I've researched it is not an issue with WebdriverIO or it's chooseFile() or uploadFile() methods. The root of the issue I believe comes down to an error in Selenium Webdriver being unable to handle the 'multiple' <input type='file' multiple> upload elements.
I fought this for a solid maybe 3 days before stumbling across this github issue:
https://github.com/SeleniumHQ/selenium-google-code-issue-archive/issues/2239
Long story short, because the HTML on imgur has the "multiple" property on it, your upload tests won't work correctly. WebdriverIO / Selenium just stops functioning from what I've noticed.
Note: I've been able to actually have my application upload a single file and add files to my system and application while testing an <input type='file' multiple>. The problem is however, that WebdriverIO and Selenium just stops. The tests end, without reporting any success or failure results.
If you go and test another <input type=file> element somewhere across the web that is NOT designated as a "multiple" upload input field you should be able to make the chooseFile() methods from WebdriverIO function correctly.
I hope this helps you and perhaps anyone else who's struggled with file uploads.
EDIT:
I've tried to make your example work, and I had success with "chooseFile()" and passing the "filepath" to it directly. Perhaps you're trying to send keyboard commands when you don't really have to? Do you have a direct file path to the image you're attempting to upload? Below is what i was able to use to successfully upload a file.
it('upload a file to imgur', function () {
browser.url("https://imgur.com/upload");
browser.waitForExist('#global-files-button');
browser.chooseFile('#global-files-button', '/insert/path/to/image.png')
})
// c:/test/image.png
var test1 = 'c:/test/image.png'
var path = test1.split('/').join('\\\\')
browser.addValue('[name="fileField"]', path )
or maybe this also work
// c:\test\image.png
var path = 'c:\\test\\image.png'
browser.addValue('[name="fileField"]', path )
or maybe this
// c:/test/image.png
var path = 'c:/test/image.png'
browser.addValue('[name="fileField"]', path )

How to load txt file in haxe in js project?

I've started a haxe js project in FlashDevelop, I need to load a local file, is this possible? how to to so?
The simple answer is use "resources". You add a path and an identifier to your hxml:
-resource hello_message.txt#welcome
And you use it in your code like this:
var welcome = haxe.Resource.getString("welcome");
Note that the operation is performed at compile time so there is no runtime overhead. It is essentially equivalent to embed the file content in a quoted string.
The complex answer is to use a macro. With them you can load, parse, process and do all the manipulation you might need. Pretty commonly, you can see macros to load a config file (say JSON or YAML) and use it as part of your application (again at compile time and not at runtime).
You could grab files with an XMLHttpRequest as long as you keep them somewhere public (if you're putting it online) and accessible to the script.
Here's a quick example of grabbing a text file from the location assets/test.txt
This is the sort of thing I usually do in the JS games I make, I find it a bit more flexible than just embedding them with -resource.
If it's not exactly what you're looking for then Franco's answer should see you through.
package ;
import js.html.XMLHttpRequest;
import js.html.Event;
class Start {
static function main() {
var request = new XMLHttpRequest();
// using the GET method, get the file at this location, asynchronously
request.open("GET", "assets/test.txt", true);
// when loaded, get the response and trace it out
request.onload = function(e:Event){
trace(request.response);
};
// if there's an error, handle it
request.onerror = function(e:Event) {
trace("error :(");
};
// send the actual request to the server
request.send();
}
}

Is it possible to use PhantomJS and Node to dynamically generate PDFs from templates?

Background / Need
I am working with a group on a web application using Node.JS and Express. We need to be able to generate reports which can be printed as hard copies and also hard copy forms. Preferably we'd like to dynamically generate PDFs on the server for both reports and hand written forms. We're currently using EJS templates on the server.
Options
I was thinking that it would be convenient to be able to use templates to be able to build forms/reports and generate a PDF from the resulting HTML, however my options to do this appear limited as far as I can find. I have looked at two different possible solutions:
PhantomJS -- (npm node-phantom module)
PDFKit
EDIT: I found another Node.JS module which is able to generate PDFs from HTML called node-wkhtml which relies on wkhtmltopdf. I am now comparing using node-phantom and node-wkhtml. I have been able to generate PDFs on a Node server with both of these and they both appear to be capable of doing what I need.
I have seen some examples of using PhantomJS to render PDF documents from websites, but all of the examples I have seen use a URL and do not feed it a string of HTML. I am not sure if I could make this work with templates in order to dynamically generate PDF reports.
When a request for a report comes in I was hoping to generate HTML from an EJS template, and use that to generate a PDF. Is there anyway for me to use Phantom to dynamically create a page completely on the server without making a request?
My other option is to use PDFkit which allows dynamic generation of PDFs, but it is a canvas-like API and doesn't really support any notion of templates as far as I can tell.
The Question
Does anyone know if I can use PhantomJS with Node to dynamically generate PDFs from HTML generated from a template? Or does anyone know any other solutions I can use to generate and serve printable reports/forms from my Node/Express back-end.
EJS seems to run fine in PhantomJS (after installing the path module). To load a page in PhantomJS given a string of HTML, do page.content = '<html><head>...';.
npm install ejs and npm install path, then:
var ejs = require('ejs'),
page = require('webpage').create();
var html = ejs.render('<h1><%= title %></h1>', {
title: 'wow'
});
page.content = html;
page.render('test.pdf');
phantom.exit();
(Run this script with phantomjs, not node.)
I am going to post an answer for anyone trying to do something similar with node-phantom. Because node-phantom controls the local installation of PhantomJS, it must use asynchronous methods for everything even when the corresponding PhantomJS operation is synchronous. When setting the content for a page to be rendered in PhantomJS you can simply do:
page.content = '<h1>Some Markup</h1>';
page.render('page.pdf');
However, using the node-phantom module within node you must use the page.set method. This is the code I used below.
'use strict';
var phantom = require('node-phantom');
var html = '<!DOCTYPE html><html><head><title>My Webpage</title></head>' +
'<body><h1>My Webpage</h1><p>This is my webpage. I hope you like it' +
'!</body></html>';
phantom.create(function (error, ph) {
ph.createPage(function (error, page) {
page.set('content', html, function (error) {
if (error) {
console.log('Error setting content: %s', error);
} else {
page.render('page.pdf', function (error) {
if (error) console.log('Error rendering PDF: %s', error);
});
}
ph.exit();
});
});
});
A really easy solution to this problem is the node-webshot module - you can put raw html directly in as an argument and it prints the pdf directly.

Resources