Display Images on HTML using MongoDB, But it didn't show - html

I have the code backend using Node.js and Front end in HTML. I tried to get the image stored in mongo to front end. But in HTML it doesn't shows the image. But when I paste the binary data of image in img src tag it works. Help plz.
index.js
function loadImages() {
let isbn=''
let imgSource=''
if (CURRENT_URL.includes('#')) {
isbn = CURRENT_URL.substr(CURRENT_URL.indexOf('#') + 1,
CURRENT_URL.length);
console.log(isbn);
}
axios.get(baseUrlLocal + '/book/image/'+isbn)
.then(response => {
console.log(response.data)
document.getElementById('imgSource')
.setAttribute(
'src', 'data:image/png;base64,' +
btoa(unescape(encodeURIComponent(response.data))) +"'"
);
})
.catch(err => {
console.log(err);
});
}
HTML
<div class="card-body" id="image-src">
<img id="imgSource" src="" alt="Red dot" />
</div>

I don't think you can do this in node.js
document.getElementById('imgSource')
.setAttribute(
'src', 'data:image/png;base64,' +
btoa(unescape(encodeURIComponent(response.data))) +"'"
);
document object is available in your browser mate. In node js you can't just use this like that. If you want to render the image you have processed, then you might want to look for a front end template engine
like
ejs
pug
handlebars
since ejs's syntax is a little bit annoying and can be very confusing sometimes you can use an alternative like handlebars take a look at here
handle bars is like a template engine. If you are familiar with Laravel or ASP.NET's Razor blade or Angular's string interpolation techniques this is very much like that so
go to your shell and install handlebars like this
npm install --save handlebars
since this is a little too much of a topic to discuss as an answer I'll just provide you with this link a tutorial on how to install and use handle bars. try that mate you will be able to achieve what you are looking for.. Cheers ...

Related

Load image if it exists or load another image in Remix

I have a bunch of goods with (or without) photos.
I need to load image if it exists or show a common (like blank) image.
the stack is
Remix, Prisma and mySQL db.
Seems like storing images in mySQL is impossible (or is it?)
Also it seems like storing image path in db would be difficult in maintenance (or it is a solution? :D)
Here is what I tried:
const getPicture= (path) => {
try{
const pic = require(`~/images/categories/${path}`)
return pic;
}
catch(err){
console.log('ERROR:', err)
return noPic;
}
}
I tryed to put this code in page, tryed to put it in loader,
tryed to put pictures to a public or private folder
(without ~ in require path ofc)
when this runs in loader it says module not found (path/to/image)
when I run this in page code it says that dynamic require isn't supported.
How or how else can I achieve the goal?
I started react and js coding this January so, well, Im a noob :D
UPD:
thank you IT goldman, that was close!
Finally all works with
<img
src={'/path/in/public'}
onError={(e) => (e.target.onerror = null, e.target.src = anotherImg)}
/>
Maybe try first
<img alt='' src={ '...'} onError={this.src='https://picsum.photos/200'}/>

Is there literally any way to get whitespace filenames to work with <img src="...">?

I have a file named "Ashen Valley-Thumbnail.jpg".
For my own sanity, I would rather not replace every single space in every single filename manually with a "valid" encoding like %20, which is the only way to fix this outside of writing a program to do it for me (which would take even longer). My goal is to be able to transfer my named files directly into the source folders (with spaces!) without having to rename them.
I've tried literally every trick in the book, namely name_of_file.replace(/ /g, "%20"), putting the name in quotes for the srcurl, and encodeURI(name_of_file), the only three answers the internet seems to have for this question. None of them worked.
I'm using React and Node.js with Express. In my server.js file, I have a fs.readdirSync block that returns all file names in a directory. The function takes the file names and tries to make an <img> from the file name and the path.
There are no errors in my code, so, I don't need to type it out. I just need someone to tell me if what I'm trying to accomplish is at all possible.
EDIT:
Some clarification:
The context I'm using <img src="..."> in:
props.artwork.map(genre => {
return(
<div className = "genre">
<h2 className = "genre-name">{genre.name}</h2>
<hr></hr>
<div>
{genre.array.map(image => {
let name = image.replace(/=|-Thumbnail|.jpg|.png/g, " ");
return (
<div className = "thumbnail">
<img src = {"/images/Artwork/Concept/thumbnails/Ashen Valley-Thumbnail.jpg"} alt = {"" + name + ""}></img> // THIS IS THE PROBLEM AREA *************
<p>{name}</p>
</div>
)
})}
</div>
</div>
)
The src above works when the file name is "Ashen=Valley-Thumbnail.jpg" and I type "Ashen=Valley-Thumbnail.jpg" in the src.
This is in React, part of a functional component's return(...)
Strictly going by your title question. It sounds like you're wondering ...
Is there literally any way to get whitespace filenames to work with
<img src=“…”>
I just tried experimenting within my own local react app by adding a basic jsx image tag to my page.
<img width="300" src={"./images/potter space media.jpg"} alt={'stack-overflow-test'} />
I then dragged a random jpg from my desktop into my project.
I was eventually able to prove that yes, you can render an image that has spaces in its name. I was able to get "potter space media.jpg" to render correctly.
See Example here:
Things to Note:
it matters where you save or store your images. Are you storing them under "./public" vs. "./src" ?
I found this question and answers helpful Correct path for img on React.js
`
You might want to take advantage of modularizing your components. This is an example of what you are trying to do. I would expect this kind of modularity from a professional PR. Otherwise, you may be doing something else fundamentally wrong. Use a custom <Img /> component for your images:
// Modular hook
function useEncodedURI(uri) {
const [encoded, setEncoded] = useState();
useEffect(() => { setEncoded(encodeURI(uri)) }, [uri]);
return encoded;
}
// Replace all <img /> with <Img />
function Img({ src, ...rest }) {
const encodedSrc = useEncodedURI(src);
return <img src={encodedSrc} {...rest} />
}
Don't use <img />. If you want consistency, just replace all <img /> with <Img />. Any decent text editor can swath over this change in a few keystrokes.

EJS rendering HTML

I've got a simple blog app on Express and MongoDB, using EJS to render my data.
The problem I have is I want this to be styled like a paragraph:
<div class="show-post__content">
<%= post.body %>
</div>
The content of the post.body is: '<p>Hello there, this is a new post.</p>'
but it's rendering like this:
If the picture doesn't work, it's showing up with the brackets visible, rather than looking like an actual html p tag if that makes any sense...
Does anyone know how to get around this?
Many thanks,
Raph
I've got it:
<div class="show-post__content">
<%- post.body %>
</div>
Is the answer.
Thanks if you had a look!
To be honest, I had the similar issue a week ago
Mission was to disable javascript. I did that with sanitizer.
I sanitized user info before inserting in MongoDB.
So recommend you to do that with sanitize-html striptags.
Those packages are in npm you can download the package.
I hope you will solve the problem.
var striptags = require('striptags');
YourCollectionName.find({}, function (err, obj) {
if (err) {
//handle or throw error
}
// For all the documents, remove html tags and save
obj.forEach(function(ob){
ob.body= striptags(ob.body);
ob.save();
});
});

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'
};

Can I create links with 'target="_blank"' in Markdown?

Is there a way to create a link in Markdown that opens in a new window? If not, what syntax do you recommend to do this? I'll add it to the markdown compiler I use. I think it should be an option.
As far as the Markdown syntax is concerned, if you want to get that detailed, you'll just have to use HTML.
Hello, world!
Most Markdown engines I've seen allow plain old HTML, just for situations like this where a generic text markup system just won't cut it. (The StackOverflow engine, for example.) They then run the entire output through an HTML whitelist filter, regardless, since even a Markdown-only document can easily contain XSS attacks. As such, if you or your users want to create _blank links, then they probably still can.
If that's a feature you're going to be using often, it might make sense to create your own syntax, but it's generally not a vital feature. If I want to launch that link in a new window, I'll ctrl-click it myself, thanks.
Kramdown supports it. It's compatible with standard Markdown syntax, but has many extensions, too. You would use it like this:
[link](url){:target="_blank"}
I don't think there is a markdown feature, although there may be other options available if you want to open links which point outside your own site automatically with JavaScript.
Array.from(javascript.links)
.filter(link => link.hostname != window.location.hostname)
.forEach(link => link.target = '_blank');
jsFiddle.
If you're using jQuery:
$(document.links).filter(function() {
return this.hostname != window.location.hostname;
}).attr('target', '_blank');
jsFiddle.
With Markdown v2.5.2, you can use this:
[link](URL){:target="_blank"}
So, it isn't quite true that you cannot add link attributes to a Markdown URL. To add attributes, check with the underlying markdown parser being used and what their extensions are.
In particular, pandoc has an extension to enable link_attributes, which allow markup in the link. e.g.
[Hello, world!](http://example.com/){target="_blank"}
For those coming from R (e.g. using rmarkdown, bookdown, blogdown and so on), this is the syntax you want.
For those not using R, you may need to enable the extension in the call to pandoc with +link_attributes
Note: This is different than the kramdown parser's support, which is one the accepted answers above. In particular, note that kramdown differs from pandoc since it requires a colon -- : -- at the start of the curly brackets -- {}, e.g.
[link](http://example.com){:hreflang="de"}
In particular:
# Pandoc
{ attribute1="value1" attribute2="value2"}
# Kramdown
{: attribute1="value1" attribute2="value2"}
^
^ Colon
One global solution is to put <base target="_blank">
into your page's <head> element. That effectively adds a default target to every anchor element. I use markdown to create content on my Wordpress-based web site, and my theme customizer will let me inject that code into the top of every page. If your theme doesn't do that, there's a plug-in
Not a direct answer, but may help some people ending up here.
If you are using GatsbyJS there is a plugin that automatically adds target="_blank" to external links in your markdown.
It's called gatsby-remark-external-links and is used like so:
yarn add gatsby-remark-external-links
plugins: [
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [{
resolve: "gatsby-remark-external-links",
options: {
target: "_blank",
rel: "noopener noreferrer"
}
}]
}
},
It also takes care of the rel="noopener noreferrer".
Reference the docs if you need more options.
For ghost markdown use:
[Google](https://google.com" target="_blank)
Found it here:
https://cmatskas.com/open-external-links-in-a-new-window-ghost/
I'm using Grav CMS and this works perfectly:
Body/Content:
Some text[1]
Body/Reference:
[1]: http://somelink.com/?target=_blank
Just make sure that the target attribute is passed first, if there are additional attributes in the link, copy/paste them to the end of the reference URL.
Also work as direct link:
[Go to this page](http://somelink.com/?target=_blank)
You can do this via native javascript code like so:
var pattern = /a href=/g;
var sanitizedMarkDownText = rawMarkDownText.replace(pattern,"a target='_blank' href=");
JSFiddle Code
In my project I'm doing this and it works fine:
[Link](https://example.org/ "title" target="_blank")
Link
But not all parsers let you do that.
There's no easy way to do it, and like #alex has noted you'll need to use JavaScript. His answer is the best solution but in order to optimize it, you might want to filter only to the post-content links.
<script>
var links = document.querySelectorAll( '.post-content a' );
for (var i = 0, length = links.length; i < length; i++) {
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
</script>
The code is compatible with IE8+ and you can add it to the bottom of your page. Note that you'll need to change the ".post-content a" to the class that you're using for your posts.
As seen here: http://blog.hubii.com/target-_blank-for-links-on-ghost/
If someone is looking for a global rmarkdown (pandoc) solution.
Using Pandoc Lua Filter
You could write your own Pandoc Lua Filter which adds target="_blank" to all links:
Write a Pandoc Lua Filter, name it for example links.lua
function Link(element)
if
string.sub(element.target, 1, 1) ~= "#"
then
element.attributes.target = "_blank"
end
return element
end
Then update your _output.yml
bookdown::gitbook:
pandoc_args:
- --lua-filter=links.lua
Inject <base target="_blank"> in Header
An alternative solution would be to inject <base target="_blank"> in the HTML head section using the includes option:
Create a new HTML file, name it for example links.html
<base target="_blank">
Then update your _output.yml
bookdown::gitbook:
includes:
in_header: links.html
Note: This solution may also open new tabs for hash (#) pointers/URLs. I have not tested this solution with such URLs.
In Laravel I solved it this way:
$post->text= Str::replace('<a ', '<a target="_blank"', $post->text);
Not works for a specific link. Edit all links in the Markdown text. (In my case it's fine)
I ran into this problem when trying to implement markdown using PHP.
Since the user generated links created with markdown need to open in a new tab but site links need to stay in tab I changed markdown to only generate links that open in a new tab. So not all links on the page link out, just the ones that use markdown.
In markdown I changed all the link output to be <a target='_blank' href="..."> which was easy enough using find/replace.
I do not agree that it's a better user experience to stay within one browser tab. If you want people to stay on your site, or come back to finish reading that article, send them off in a new tab.
Building on #davidmorrow's answer, throw this javascript into your site and turn just external links into links with target=_blank:
<script type="text/javascript" charset="utf-8">
// Creating custom :external selector
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/)
&& (obj.hostname != location.hostname);
};
$(function(){
// Add 'external' CSS class to all external links
$('a:external').addClass('external');
// turn target into target=_blank for elements w external class
$(".external").attr('target','_blank');
})
</script>
You can add any attributes using {[attr]="[prop]"}
For example [Google] (http://www.google.com){target="_blank"}
For completed alex answered (Dec 13 '10)
A more smart injection target could be done with this code :
/*
* For all links in the current page...
*/
$(document.links).filter(function() {
/*
* ...keep them without `target` already setted...
*/
return !this.target;
}).filter(function() {
/*
* ...and keep them are not on current domain...
*/
return this.hostname !== window.location.hostname ||
/*
* ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
*/
/\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
* For all link kept, add the `target="_blank"` attribute.
*/
}).attr('target', '_blank');
You could change the regexp exceptions with adding more extension in (?!html?|php3?|aspx?) group construct (understand this regexp here: https://regex101.com/r/sE6gT9/3).
and for a without jQuery version, check code below:
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (!links[i].target) {
if (
links[i].hostname !== window.location.hostname ||
/\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
) {
links[i].target = '_blank';
}
}
}
Automated for external links only, using GNU sed & make
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated by adding above sed command to a makefile. For details, see GNU make or see how I have done that on my website.
If you just want to do this in a specific link, just use the inline attribute list syntax as others have answered, or just use HTML.
If you want to do this in all generated <a> tags, depends on your Markdown compiler, maybe you need an extension of it.
I am doing this for my blog these days, which is generated by pelican, which use Python-Markdown. And I found an extension for Python-Markdown Phuker/markdown_link_attr_modifier, it works well. Note that an old extension called newtab seems not work in Python-Markdown 3.x.
For React + Markdown environment:
I created a reusable component:
export type TargetBlankLinkProps = {
label?: string;
href?: string;
};
export const TargetBlankLink = ({
label = "",
href = "",
}: TargetBlankLinkProps) => (
<a href={href} target="__blank">
{label}
</a>
);
And I use it wherever I need a link that open in a new window.
For "markdown-to-jsx" with MUI v5
This seem to work for me:
import Markdown from 'markdown-to-jsx';
...
const MarkdownLink = ({ children, ...props }) => (
<Link {...props}>{children}</Link>
);
...
<Markdown
options={{
forceBlock: true,
overrides: {
a: {
component: MarkdownLink,
props: {
target: '_blank',
},
},
},
}}
>
{description}
</Markdown>
This works for me: [Page Link](your url here "(target|_blank)")