Input/Set/Change HTML img src with Node JS - html

I have a NodeJS server which allows users to upload images to a directory. I'm trying to build a system that will get an image in this directory depending on the currently authenticated user and output it to an HTML Page
I'm trying to find a way to set the img src through NodeJS but am unable to do so.
<html>
<body>
<img src="user1.png" />
</body>
</html>
Everywhere I have checked, the Front-end has the filename explicitly entered into the img src tag, but since I need this tag to be set according to the user I can't enter the link of a single image in the tag. Should I make a separate HTML page for each image or is their a different solution to this problem through Node?
I have also stored the path to each image in a MySQL table with adequate measures recognise it for the required user. Is there a way I can use this to input into the img src tag?
module.exports.getImage= function(req,res){
var imageid = req.body.id;
var imagesql = 'SELECT path FROM Image WHERE id = ?';
var imageinsert = [imageid];
certsql = mysql.format(imagesql, imageinsert);
connection.query(imagesql, function(error,results, fields){
if(error){
console.log(error)
res.status(401).send('query error');
}
else{
console.log(results)
res.status(200).send(results);
}
})
}
The snippet above gives the path in results.
I am using express and storing the user token in cookies.
Ejs didn't work, is there any other way I could get solve this problem?

Store some type of user id in session and get data according. Load
the above html in ejs view engine and set the src attribute as file
gotten from the directory.

Related

Update html file content

I worked on a little startpage for my browser. Now I would like to make some changes to it, so it updates the index.html file depending on a text file, when this got changed. What whould be an efficiant way to solve this problem?
My approach would be to create a text file and read line by line from it and update the html file. In the text file I would store the links shown on my startpage - I thought maybe something like this:
|cat_media
https://mailbox.org,mail
https://netflix.com,netflix
...
http://crunchyroll.com,crunchy
https://jott-uh-be.bandcamp.com,bc
|cat_social
https://pr0gramm.com,pr0
https://stackoverflow.com,stackoverflow
https://twitter.com,twitter
https://instagram.com,insta
When the line starts with the symbol |, it creates a new <div> with the class category and the string in that line (e.G. class= 'category cat_media'). Otherwise, if the line starts with http, it will add a href-link (e.G. <a href='https://mailbox.org'>mail</a>) to the html-code.
I got this website hosted on my raspberry pi with nginx and uploaded it to my github pages.
You don't have to update the index.html file.
You can create dynamic content.
You can use PHP:
You can learn it here:
https://www.w3schools.com/php/default.asp
And here is how to read a file
http://php.net/manual/en/function.fread.php
Or if you cant use PHP you can use Javascript:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(() => {
$.ajax({
url:'your-config-file.xt',
success: function (data){
console.log(data); //this is the config file. just for loop it and modify the dom
}
});
});
</script>
But your config file must contains the string how the links should be shown.
For example:
|catergory one
yt: https://www.youtube.com

Angular 4: Setting img src base href inside of innerHTML

In my Angular 4 app, I am using innerHTML to show description of the exercises which are in HTML format.
<li *ngFor="let exercise of exercises">
<div [innerHTML]="exercise.longDescription"></div>
</li>
These descriptions can also contain images
<img src="/file/na\6ad7k4ynon6yh2qcibcdqxwcey.jpg">
and that is where I am struggling because I need to set the base href for these images to localhost:8080 where my backend is. Angular is trying to get them from standard localhost:4200 (ng serve) so I am getting errors.
Any idea how to do that?
Found a solution, not sure if is the cleanest one but it gets the job done.
I created a function in my exercise model that adds environment.URL to the src (which is localhost:8080 for development and server's API for production).
public getHTML () {
return this.longDescription.replace(/<img src="([^"]+)">/, '<img src="'+environment.URL+'$1">');
}
and I access it like this
<div [innerHTML]="exercise.getHTML()"></div>
instead.
Environment const looks like this:
export const environment = {
production: false,
URL: 'http://localhost:8080'
};

How to add images in an html file?

Anytime I have read an article on html and images, I have seen an anchor tag like this:
<img src="http://www.tizag.com/pics/htmlT/sunset.gif" />
However, in my case I have stored the image in AWS-S3 and I am reading image from S3. This, I do not upfront have a path like "http://www.tizag.com/pics/htmlT/sunset.gif"
So what is the most common technique to embed image in the html page when image is stored in S3, and the path to image is not known ?
In case my question is confusing, I will ask it differently.
I am building a project, which is simple. Whenever user is logged in he gets a page saying "Welcome" and below welcome note is is profile picture.
But, assume I have 10 users, each of these 10 users will have a different URL to the image.
eg:
<img src = "http:bucket.amazonaws.com/USER1'> for user 1
<img src = "http:bucket.amazonaws.com/USER2'> for user 2
and so on.
So the image I will display is not known until run-time and path to image is dependent on who logs in.
How to make my HTML page smart so that the image src is not a constant and can be made flexible depending on who logs in ?
SOLUTION IN JSP, WHICH I COULD DO, THANKS TO SO MANY ANSWERS:
<body>
<% String url = (String)request.getAttribute("url"); %>
<img src = <%= url %>></img>
</body>
This JSP code is called from the servlet.
request.setAttribute("url", "URL to image.");
RequestDispatcher view = request.getRequestDispatcher("URLImage.jsp");
view.forward(request, response);
You require some kind of server side programming language to generate the the paths for the image dynamically for each user. Anyway you do have a setup for the users to login. For that, I believe you have some kind of framework in some server side scripting language like PHP(Laravel, Wordpress, CodeIgniter), Java(Spring), Ruby(Rails), Python(Django).
So when a user logs in, your login script should validate the user and you will render a particular html page. And you should show the name of the user and a particular image. In PHP or Ruby on Rails you can embed the actual PHP code or ruby code in HTML.
In PHP, like this :
<html>
<head> </head>
<body>
<!-- say PHP Session varibale contains the logged in user's name & bucket name -->
<img src="<?php echo "https://"+ $_SESSION["bucket_name"] +".amazonaws.com/"+$_SESSION["username"] ?>" />
</body>
</html>
In Ruby on Rails, like this:
<html>
<head> </head>
<body>
<!-- say Ruby - Rails controller passes #username & #bucketname to view -->
<img src="<%= "https://"+ #bucketname +".amazonaws.com/" + #username %>" />
</body>
</html>
In Python - Django, like this :
<html>
<head> </head>
<body>
<!-- In Python - Django Suppose you pass context variables username & bucketname to template -->
<img src="https://{{ bucketname }}.amazonaws.com/{{ username }}" />
</body>
</html>
So what I would suggest is, you get familiar with the server side scripting language that you intend to use or are already using and manipulate the url to be generated based on logged in user accordingly.
If your bucket was named my-bucket and the image file was named my-image.png, then the format for the url would be http://my-bucket.s3.amazonaws.com/my-image.png.
In order to access the file though, you need to have a policy attached to your bucket that allows anyone to access the file. Below is a policy that works for this example.
{
"Id": "some-policy-id",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "some-statement-id",
"Principal": "*",
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::my-bucket/my-image.png"
}]
}
See the docs for more information about accessing a bucket.
Also note that the bucket name must be DNS compatible for this to work. See here under Rules for Bucket Naming.
My suggestion is:
<img src = "http:bucket.amazonaws.com/USER1'> for user 1
<img src = "http:bucket.amazonaws.com/USER2'> for user 2
according to your examples in user1 and user2 having same path is http:bucket.amazonaws.com/ make it common for all and put variable after that and according to your user id fetch image from there.
like <img src = "http:bucket.amazonaws.com/<?php echo $userimg; ?>'
or fetch img path from database according to users
You can use javascript / jQuery:
<script type="text/javascript">
$(document).ready(function(){
var userName = getUserNameValue;
document.getElementById("<%= loginImg.ClientID %>").src = "http:bucket.amazonaws.com/" + userName;
});
</script>
with html:
<img id="loginImg" src="default.img" />
You should be able to handle this like a simple 'insert your name here' kind of Hello World exercise.
Since the user is logged in, you should have at least some sort of information from the user, or can get it - username, first/last name, uniqueID, etc. Ideally when the user logs in, your server will provide you with an image filename, but whatever.
Store that uniqueID into a variable in your JS. This will be used to build your URL in JS.
Then, have the root path of your images in a separate variable.
var uniqueID = 'avatar_e2fbfbcbb52d_128'; // from login
var urlPrefix = 'http://www.tizag.com/pics/htmlT/';
var imageURL = urlPrefix + uniqueID + '.gif';
var imgNode = document.createElement("IMG");
imgNode.src = imageURL;
document.getElementById('imageDiv').appendChild(imgNode);
Then, in your HTML,
<div id='imageDiv></div>
I can tell you the approach since you don't have a code to edit or look into.
You can have an ajax call to your server once the user logged in, get the image URL from there or if you are having any back-end language then get the url from there.
Now the hard part, assigning the URL to the img source tag, so if you are doing the ajax call just store the data(URL) into the JavaScript variable and give img src as that variable, if you are doing it using server side language then also you can do the same, different languages have different way to do it and you need to google it out, or you can have the hidden field with id, assign that hidden field that value (URL) in your JSP or ASP page and use that in the img src.
Hope the approach works. I am a dot net developer and you are java developer so can't tell you the exact code.
Its very simple just try this out. I have added your image path just run this code.
<!DOCTYPE html>
<html>
<body>
<h2>Spectacular Mountain</h2>
<img src="http://www.tizag.com/pics/htmlT/sunset.gif" style="width:304px;height:228px;">
</body>
</html>

Displaying IMG from data in panel created with HTML Services

I have a sidepanel, its code get data uri image from server (specifically from a Google Docs, by using google.script.run).
I need to display it, I'm trying to do so on an IMG tag in the HTML document, but the sandbox forbid to assign anything to img.src .
Any ideas, instead of using templates? Because I want to change the image dynamically.
Thank you
If you are working inHtmlService.SandboxMode.IFRAME mode you can pass the base64 to the image src. Below is an example of using a template to do this.
code.gs
function doGet() {
var t = HtmlService.createTemplateFromFile('index');
t.icon = icon;
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
index.html
<div>
<img src="data:image/png;base64,<?=icon?>"/>
</div>
icons.gs
var icon = 'iVBORw0KGgoAAAANSUhEUgAAACYAAAAmCAYAAACoPemuAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAZOSURBVFhHzZh5bFRFHMe/b+/tHrQUBFYwlAoYqFQioCBVQsUSEYiQoIKYIrEEECQkTYQECVGBQGMjCVCpCVZpCKCVRP8gXDElxoRQjlZBgV6AW46edLe7b4/3/M3s1Lbsvu0hbfxkZ9+b35vjO7/9zbyZlWZ/7lHxP0QnrtqQbFXlX8LQR6g+b4I3031b8YXpTDAl2mBy2KGz2AFJHxHZC3hxvRn6BDvMThsMdhvZJPaEP9dCWxiJUpt+x4kPJZTtGou6s5thNYZhsNmpSSnSoc5IWs2QDFaeoLdQnuq1D4DasNLApMYLqDr6Ns59nICrX6TSQJm4SDdaaMaYzmhD86X9uHB4jbBESJv9AVKWHOAj8t2tgv/hfahyE/yyDIcjCSGDA/ah42AYbId8pxoVX8+C+86tSGXCSM7KzFche9vY8IQ1Gk1heosN1T+txs1fCoSlAyOpCioio4HZAMghkXmEebu9aAtKkFTtRjR/SolG5pODIteV7kQxtEQxAp4H1H434S2uUbDBOB2DRO7xYrZ2H2OawhRFRfLYLJF7vIQU+hnZTxKHmMLYYExWCTVnP4sYYjBixAisWrVK5HrHxb0vwDyIZm8ct0ULo8I6QwLarpbgzrVzwhiNTLOwoKAAp0+fFpaec//vSsg3zkSWGA2ihKnkYmOChIqjOcISm/bRZmZm8vuMjAye7ylXj2+Eyaa9YEcJkySa560NaGxoEJaeUVpaiuLiYpHrnrvV5VB8fkg6vbB0RdfcpqJzeigb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Y/R4oY5Zg3s4GTKK9U9qcdXj+jVyMnjiDlzAZaRvefprmMzeCEo59UO4NcYQRLN5InE+x4Qna0A2fuwfJWbswLO1NUaD/iC+M4IGrhugtQd7zUaIZqwQjy0F/0q2wDkhgH2ZXX+mFsE6IP0RUWsXZ64rf821CBJU8zOBP+tZDH6pRb3JbZM2yj34FltBdfm8yD8LgRCe/t4+cAXa+kilJnhb6in12jEevhDHvGNQgWh/cwNRlBRg1/SPojVZMnLcFQycvx5TcKjw1eQHcZT/gtb0qpiz/Bg0V3/O/OsmNopWeAPwDzbZglh6+UyAAAAAASUVORK5CYII=';

How to set ContextPath for an image link

i am trying to put context path for an image in HTML.<img src="/MyWeb/images/pageSetup.gif">
Here /MyWeb is the ContextPath which is hardcoded. How can i get dynamically.
i am using as <img src=contextPath+"/images/pageSetup.gif">but image is not displaying. Is there any option.
First of all, "Context path" is a term which is typically used in JSP/Servlet web applications, but you didn't mention anything about it. Your question history however confirms that you're using JSP/Servlet. In the future, you should be telling and tagging what server side language you're using, because "plain HTML" doesn't have a concept of "variables" and "dynamic generation" at all. It are server side languages like JSP which have the capability of maintaining and accessing variables and dyamically generating HTML. JavaScript can be used, but it has its limitations as it runs in webbrowser, not in webserver.
The question as you initially have will only confuse answerers and yield completly unexpected answers. With question tags you reach a specific target group. If you use alone the [html] tag, you will get answers which assume that you're using pure/plain HTML without any server side language.
Back to your question: you can use ${pageContext.request.contextPath} for this.
<img src="${pageContext.request.contextPath}/images/pageSetup.gif">
See also:
How to use relative paths without including the context root name?
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
You can't write JavaScript in the src attribute. To do what you want, try some code like this:
var img = new Image();
img.src = contextPath + "/images/pageSetup.gif";
document.getElementById('display').appendChild(img);
Here the target; the place where you want to display the image, is a div or span, with the id display.
Demo
With HTML, you'll have to take some extra traffic of producing an error, so you can replace the image, or you can send some traffic Google's way. Please do not use this:
<img src='notAnImage' onerror='this.src= contextPath + "/images/pageSetup.gif" '>
Demo
Do not use this.
You must use JavaScript for this.
First, have all images point to some dummy empty image on your domain while putting the real path as custom attribute:
<img src="empty.gif" real_src="/images/pageSetup.gif" />
Now have such JavaScript code in place to iterate over all the images and change their source to use the context path:
var contextPath = "/MyRealWeb";
window.onload = function() {
var images = document.getElementByTagName("img");
for (var i = 0; i < images.length; i++) {
var image = images[i];
var realSource = image.getAttribute("real_src") || "";
if (realSource.length > 0)
image.src = contextPath + realSource;
}
};