Load image if it exists or load another image in Remix - mysql

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

Related

Redirecting to alternative page if a linked document from <a> not found

I'm looking to see if there is some way to provide an alternative link for a hyperlink to follow if the primary doesn't exist, similar to an image 'alt'. I know 'onerror' exists but it doesnt seem to work for html links. I'd like to avoid JS if possible. If its unavoidable I'm willing to explore its options however.
So in short, if I use:
Link
If it cant find 'TestFile.html', I'd like it to redirect to somewhere else, say TestFile2.html.
<button onclick="onclick()">redirect</button>
<script>
const fs = require('fs')
const path = './TestFile.html'
function onclick() {
try {
if (fs.existsSync(path)) {
//file exists
return res.redirect('/server/TestFile.html');
}
} catch(err) {
//file unknown
return res.redirect('/server/TestFile2.html');
}}
</script>
This should work! But it might not, because I suck at coding and this is a Frankenstein of multiple online sources. Thank You!

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.

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

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 ...

ng-src not showing up for my img array

I have a simple image viewer webpage on gitpages but before I push the next group of images I want to condense all of my images into an array using angular.
The test I have made here uses only 4 photos that are in the same folder as every other file.(they are jpegs)
my js file is set up like this with a factory for the array and a controller.
angular.module('beamModule',[])
.factory('imageFactory', function(){
return {
getImages: function(){
return ['beam1.jpg','beam2.jpg','beam3.jpg','beam4.jpg'];
}
}
})
.controller('Photos', function(imageFactory){
this.images = imageFactory.getImages();
});
I don't think anything is wrong with this array but maybe I am overlooking something?
The HTML that I am using and the section that is giving me trouble when I check the developer tools is below.
<div class="imgcontainer" ng-controller="Photos as photosController">
<img ng-repeat="src in photosController.images"
ng-src="beamModule.js/{{images}}">
</div>
I am not sure if I am supposed to be using an ng-class attribute in the css or if there is something else that needs removed?
The developer tools are returning this value for each of the images (they are repeating just not showing)
<img ng-repeat="src in photosController.images" class="ng-scope">
Why is the ng-scope class being put in here and the ng-src is being removed?
EDIT FIXED
Ok to the person who answered so quickly and simply you are the real mvp here.
You said to change the ng-src="beamModule.js/{{images}}" to read {{src}} instead.
Once I tried this it still didnt work but then I checked the dev tools and noticed it was attempting to pull the files from the js file and not the actual file so I just changed it to this and now it works great! Thank you.
ng-src="{{src}}"
The ng-src attribute needed to point to the repeat instead of the js file.
ng-src="{{src}}"

EmberJS set active class for dynamic linkTo on menu when direct accessed

i've been trying this since last week, to make the active class work on those dynamic links:
<li>{{#linkTo tag 'bw'}}Black and White{{/linkTo}}</li>
<li>{{#linkTo tag 'instax'}}Instax{{/linkTo}}</li>
<li>{{#linkTo tag 'digital'}}Digital{{/linkTo}}</li>
I put a code running here: http://jsbin.com/opuzop/1/edit so if you feel ok to help me with that would be great :D it's my photo portfolio as well.
Also, if I try to upload to the newer version of Ember, some stuff stop to work, like the JS I created on
App.GeneralView = Ember.View.extend({
didInsertElement: function() {
if(this.$() !== undefined){...
It was created to load after the view render, so I do a image resize and a body resize too, and set everything horizontal, but with the newer version it only work when accessed directly.
Also, sometimes it don't get the JSON from Tumblr and stop working.
I'm not sure, but I think it has to do with the serialization of your object, try adding something like this in your "App.TagRoute" route:
serialize: function(param) {
return {tag: param.tag}
}