vue.js dynamic image load [duplicate] - javascript

I have a problem with images recently. Everything is ok until you have to show a list of images on the page.
The problem is that when we directly give an src for image with hardcoded string, it works with a url like ~/assets/any-image.png. But if I try to move url into any variable / object / array, I have to specify the :src="myVariable" which contains the URL.
The code for example:
<template>
<div>
Problem with images
<img :src="image.url" alt="">
<img :src='require(image.url)' alt="">
</div>
</template>
<script>
export default {
data () {
return {
image:
{
url: '~/assets/icon.png',
type: 'asset'
}
}
}
}
</script>
Here I tried using assets with ~ and #, also with and without slash. Of course the image exists in assets folder, but since the src url is provided via any variable (not directly), the assets url is not served and as a result the image url looks like host:port/~/assets/... which doesn't exist on the server.
In this example I've got an idea to replace image url with an object containing the url and its type (asset/static) and make checks if type asset, then use require(variable) but got the problem that "Cannot find module '~/assets/icon.png'"
Has anybody solved this problem?

You need to use require when binding to an asset variable image. For example:
<img :src="url">
url: require('#/assets/icon.png')
If your json contains only the filename, you can place require in the template:
<img :src="require('#/assets/' + url)">
url: 'icon.png'

Thanks to Dan with his answer
I've got a final solution which is universal:
Image contain it's link and type:
image: {
url: '/any-asset-folder/image.png'
type: 'asset'
}
Then with ternary operator result is
<img
:src="image.type === 'asset'
? require('#/assets'+image.url)
: image.url"
>
In this way I've got images working both if they are from assets or static or external :)

Related

Load images dynamically with webpack

I'm running a webpack web app on AWS S3 and I have to dynamically show images. I found this following code thanks to this post:
getImgUrl(nameImage) {
let images = require.context("../static/images/members/", false, /\.jpg$/);
return images("./" + nameImage + ".jpg");
}
And in my vuetify template:
<template v-else-if="activeTab == 0">
<img
:src="getImgUrl(chunk[i-1])"
/>
</template>
The problem is the images are not loaded as my aws server returns a 403 Forbidden error strict origin when cross origin.
That's weird because I don't have any problem with another image that I load in my topbar with this code:
<v-img
:alt="appName"
class="shrink mr-2"
contain
:src="require('../static/images/logo.jpg').default"
width="40"
height="40"
/>
Do you have any other idea how I could require my images dynamically ?
Nevermind, I just had to add .default to the value to return:
getImgUrl(nameImage) {
let images = require.context("../static/images/members/", false, /\.jpg$/);
return images("./" + nameImage + ".jpg").default;
}
Remember kids: if require() doesn't work, just add .default at the end #SuperSmart
To be true I didn't understand why I had to do this, but if you know feel free to tell me in the comments

ReactJS: How to properly link to a download file?

I have a manual.pdf file that I need to attach to my document.
The conventional wisdom would be to link the file source in the href attribute of an <a> tag:
<a href="../assets/img/manual.pdf" download>Manual</a>
React seems to not like it, I assume. Failed-No file error is given upon click on the <a> tag.
When it is an <img> tag with a local file, I would import the source import logo from '../assets/img/logo.svg';, then pass it to the src attribute like so <img src={logo} alt="brand logo" />.
I tried it - no use.
giving the absolute path - no use.
giving a relative path - no use.
It seems that it does not work the same way with <a> tags.
How do I properly link local files in a React Project?
P.S. I have heard of React routes, but I am not linking to any page, it is for downloading a file.
Try this
<Link to="/files/manual.pdf" target="_blank" download>Download</Link>
Where /files/manual.pdf is inside your public folder
Try this one https://www.npmjs.com/package/file-saver (FileSaver.js)
//function for saving file
const saveManual = () => {
fileSaver.saveAs(
process.env.REACT_APP_CLIENT_URL + "../assets/img/manual.pdf",
"manual.pdf"
);
};
//button for calling
<button onClick={saveManual}>
Manual
</button>

How to save image link in when using 'require' to display image in VueJS?

I am trying to create a page where I show Pizza items with their images. The Pizza object is saved in the DB with a field imgUrl. The image is not getting displayed but I see the alt text that I provided but I can see in the console that the image link is correct.
Right now, the imgUrl field in the database has data like ../assets/images/pizza.jpg. Should I instead save require(../assets/images/pizza.jpg) in the db. That looks weird. Here is the code, please look at the mounted method.
<template>
<div>
<div class="class">
<span><h1>All you can eat Menu.</h1></span>
<div class="container">
<div class="box" v-for="item in pizzaList" :key="item.id">
<div>
<img :src="item.imgUrl" alt="Image"/>
<div>
<a class="btn" #mouseenter="$event.currentTarget.style.background = '#EF6B7F'"
#mouseleave="$event.currentTarget.style.background = '#e31837' ">Buy Now</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data () {
return {
pizzaList: []
}
},
mounted: function () {
axios.get('http://localhost:8081/api/pizza/all')
.then(response => {
this.pizzaList = response.data;
})
.catch(e => {
console.log(e);
})
}
}
</script>
I have already read
Vue and API: Displaying Image
Image path in Vue JS
How to reference static assets within vue javascript
but what these answers are telling is how to do when we have hardcoded the url, we should encapsulate it with require but they do not tell when we are getting the link from the DB, how do we put require in the html tag.
I hope my question was clear. Please ask for details if you need. thanks
The reason it was not working was because
Webpack's require() needs at least some part of the file path to be completely static and we should "make only part of the path dynamic"
that means you cannot put the entire image path in the DB and in the UI pass it to require and expect it to work
I replaced
<img :src="require(`${item.imgUrl}`)" alt="Image"/>
where item.imgUrl = '../assets/entities/pizza/pizza_1.jpg' (which is the entire image path relative to the component)
by
<img :src="require(`../assets${item.imgUrl}`)" alt="Image"/>
where item.imgUrl = '/entities/pizza/pizza_1.jpg'
This answer mentioned by Michal Levy up in the comments explains all this
https://stackoverflow.com/a/64208406/8147680

Display images in React using JSX without import

The problem I faced is with the img tag. When a single image is concerned,
The below code loads the image:
import image1 from './images/image1.jpg';
<img src={image1} />
But the below code doesn't load:
<img src={'./images/image1.jpg'}/>
or
<img src='./images/image1.jpg'/>
I need to loop through json, something like:
[{'img':'./images/image1.jpg','name':'AAA'}, {'img':'./images/image2.jpg','name':'BBB'}]
Plus, display each of them as image with name as footer. Looping is fine but the images doesn't load. It is not actually possible for me to import every images to add. I don't use anything other than JSX as of now. Please favour.
You need to require the file like so:
<img src={ require('./images/image1.jpg') } />
We could use require instead of import statment.
Like ,
<img src={require("folder/image.format")} alt="image not found" />
But if you run it , it will show image not found!!!
We could simply solve it by changing the statment by adding .default
let image = require("folder/image.format");
<img src={image.default} alt="image not found" />
require is used for static "imports", so you just need to change your imports.
Example:
var imageName = require('./images/image1.jpg')
<img src={imageName} />
I just tried this, it works!
import I01d from '../../styles/images/01d.png';
....
<img src={this.getWeatherIconImage(iconCode)}/>
getWeatherIconImage(icon) {
switch (icon) {
case '01d': return I01d; ...
default: break;
}
}
The suggested answers do not appear to work any more. Here is a code fragment that highlight the issue.
import React from 'react';
import importImg from '../images/img.jpg';
export default function ImgTest(){
return(<>
<img src={importImg} alt='import'></img><br/>
<img src={require('../images/img.jpg')} alt='require function fails'></img><br/>
</>)
}
When this code is rendered, the following occurs.
1st displays the image - it the expected result
2nd displays the alt "require function fails" - is not the expected result
Its because, you've put your images folder in src folder. So you should import or require it. You can directly put the source of image if it's placed in public folder without importing or using require, like this.<img src='/images/image1.jpg' />

angular Failed to load resource error in inspector

I am uploading dummy content using angular's ng-repeat.
var app = angular.module("homeApp", []);
app.controller("entriesView", function ($scope){
$scope.itemEntry = [
{
image: "img/112013-priscilla-600.jpg",
title: "ymc",
logo: "http://www.youmustcreate.com/site/wp-content/themes/youmustcreate/images/core/header-logo.jpg"
},
{
image: "https://cms.myspacecdn.com/cms/x/13/47/112013-priscilla-600.jpg"
}
];
});
HTML
<section class="miniframe-wrapper" ng-controller="entriesView">
<section ng-repeat="itemEntry in itemEntry" class="miniframe">
<img src="{{itemEntry.image}}" alt="img"/>
I noticed in inspector i am getting the Failed to load resource error however the images are appearing on my browser. Does anyone know what exactly is causing this issue. am i referencing my images correctly?
Use ng-src instead of src in your image tags when using string interpolation. ng-src parses the string then assigns the src to the tag while vanilla html is looking for an image called "{{dataEntry.image}}"

Categories

Resources