How to add images in an html file? - html

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>

Related

2sxc - Access an adam file by unique identifier

I need to access an ID to an adam file setup like this:
MyDocument is the field name, where users can load an image or whatever.
In a list style view, users will click a link that activates a detail view for that image.
The link will be something like mysite.com/mytab/detailsforfile/fileId
The details view will parse the fileId and load the image.
So, two questions:
How can I access an ID for that adam file that later allows me to load that file based on that id?
How can I access the URL of the file based on the ID created?
Is the native DNN file: 123 the only way? Or does 2sxc or adam have some specific ids?
Edit:
A practical example would probably help:
This list view will have:
#foreach(var car in eCars) {
<div>
<strong>#car.Name</strong>
<img class="img-fluid" src="#car.carImageOne">
See full image...
<img class="img-fluid" src="#car.carImageTwo">
See full image...
</div>
}
And the details view:
#{
var qsImageId = Request.QueryString["whatever"];
//cast and double check the qs int
var imageURL = ??; // How do I get the file url based on the id?
}
<div>
//embed nice frame, ads, whatever
<img class="img-fluid" src="#imageURL">
</div>
The IDs are normal IDs from Dnn/Oqtane
To get the "raw" data use the Get method, and set convertLinks: false - see
https://docs.2sxc.org/api/dot-net/ToSic.Sxc.Data.IDynamicEntity.html#ToSic_Sxc_Data_IDynamicEntity_Get_System_String_System_String_System_String_System_Boolean_System_Nullable_System_Boolean__
To then get the file id back could be challenging. The 2sxc APIs aren't for public use and could change, so probably best to use DNN APIs to get it.
Alternative is to pass the entity-id to the details page, and there just get the entity and work with that - which is probably much easier.
To get the file ID I used this:
var getFile = AsAdam(Entity, "field").Files as System.Collections.Generic.IEnumerable<dynamic>;
get fileId = getFile.First().FileId;
To get the url from the id:
var myFile = FileManager.Instance.GetFile(FileId);
var myurl = FileManager.Instance.GetUrl(myFile);

Trying to switch between local and public webpage while looping through data

At the moment, I am trying to list projects on a website in a grid. Some of them link to another page on the site and others link to another domain page. At the moment I am using React-Router's 'Link' to go from one page to another, however this doesn't work when going to a page outside of the domain. In the JSON file, I check for the 'url' variable which returns either the URL if its public or 'project-page' if it is local. I can't figure out how to differentiate between the two in JSX; is there a work around while still utilizing the JSON file?
<div className="projects">
{projectData.map((projectDetail, index) => {
return(
<div className='project-card'>
<Link to={projectDetail.url}>
<img src={require('./images/icons/' + projectDetail.alt + '.jpg')} alt={projectDetail.title}/>
<h3>{projectDetail.title}</h3>
<p>{projectDetail.subtext}</p>
</Link>
</div>
)
})}
</div>
Well, to differentiate you can check the content of the projectDetail.url you are retrieving from that JSON in your javascript file, if that matches your domain (your website - having a project-page as you mention) or is it an external domain. You can also set a flag value in your json file. For each project set a value (e.g externalUrl: 1 or 0) and then check if projectDetail.externalUrl is 1 (it contains an external link). Then, maybe try the following for external domains:
<Link to={{ pathname: "external URL" }} target="_blank" />
In your case:
<Link to={{ pathname: projectDetail.url }} target="_blank" />
See this answer for detailed information: React-Router External link
Edit 1
If Link does not work for external websites, this would probably be related to the version of react-router you are using. Actually, to navigate to external websites you can as well use anchort tags <a> to redirect. Check what URL your project has and then conditional render a <Link> or <a>.
<a href="www.example.com" target=_blank></a>

How to get clicked img src and pass it to the next view function

I am using flask to deploy my model for image similarity search. To run it, I will have two pages:
1) first page (say, query.html) that shows a randomly generated image from my dataset; users can continue to refresh this page till they see an item that they like. In html, it would be something like <img src="{{ random_path }}" alt="">. When the user is satisfied, the image needs to be clicked to direct to the next page;
2) second page (say, results.html) that takes the img src from the first page, and run the model at backend and return the similar images.
I am now confused how I should link step 1) to step 2) - how to get the img src on click and pass that information on to the next step?
You can use a form with hidden input tags and make a post request (More on flask's post request here) to pass on the data from one page to the other. In code it would look something like this:
HTML:
<html>
<body>
<form action = "/imagematch" method = "post">
<p><input type = "hidden" name = "imagesrc" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
Python Backend:
#app.route('/imagematch',methods = ['GET', 'POST'])
def login():
if request.method == 'POST':
user = request.form.get('imagesrc')
Alternatively you can use JavaScript localstorage/sessionStorage. More on localstorage here:
Write a <form> and place the <input type="hidden"> (with base64 format of the image as value) or <input type="hidden"> (with the server file path as value) whichever comfortable and upon submitting the form the image path/base64 format of the image as value will be sent to server.
Or
Using Javascript or JQuery upon user selects the image, send the image to the server via a AJAX request and do whatever you want at the server-side and return the status to the user accordingly.
Option 1 is simple and straight forward and you need to deal with base64 conversion.
Option 2 is a little complex and needs good JQuery expertise.

Input/Set/Change HTML img src with Node JS

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.

Search and replace in htm files

I am a technical writer and in the process of importing our content (HTM) into a new platform (Still HTM format). During this process I also want to use Prettyphoto to give users the ability to click on screenshots to vew a bigger version.
I have this now in my html code:
<a rel="prettyPhoto" href="images/xxxxxxx"><img src="images/23456.png" class="screenshot" alt="some alt text" />
There are thousands of files and each file could have many such images in them. where the name of the image changes but the href="images/xxxxxxx is the same
I need the xxxxxxx for each instance to be replaced by the png filename 23456.png or whatever that may be.
Is there an easy way to do this and how?
Thanking all in advance
You could use jQuery for that. The function loops all items with the class screenshot. Read the src property and puts that in the parent href.
<script type="text/javascript">
$(document).ready(function () {
$('.screenshot').each(function () {
$(this).parent().prop('href', $(this).prop('src'));
});
});
</script>
However this is no SEO friendly. If you want the href to be available in the source you are gonna need a server side solution with some programming.