How to display an image in Angular from a static backend path?
Solution 1
After your contribution I could solve this. But the problem wasn't in the frontend but actually in the backend. However, your contributions have helped a lot to make my code better, so I'll give the credits to everyone which I could implement or follow the suggestion in my final solution.
Even those who I didn't quote, I'm really grateful for your time trying to help me!
1st. Credits to @HenryDev
Have you tried putting the image type in the URL? and check if you are able to see the image? just put this in the URl localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg and tell us what you see
After I tried it I started thinking that something was wrong with my backend, because of the return of this try was the json instead of the image rendering.
2nd. Credits to @Thatkookooguy
Using specific res.sendFile:
app.get('/avatars/:name', function (req,
res, next) { const fileName = req.params.name;
res.sendFile(fileName, options, function (err) { /* ... */ }); });
On the backend I was using the route to find the avatar saved in the database with the same path '/avatars/:id'
. So everytime I tried to access it, the priority was the route.
Because of that, when I tried access the image by taping the path on browser, it retuned the json file instead of display the image.
SOLUTION
So, the solution was to replace the route to call the function to fetch the image list!
However, as I told you, I got a lot of tips here which gave me the opporunity to improve my code:
3rd. Credits to @Ian Halfpenny
You can overcome security in place by Angular by using bypassSecurityTrustResourceUrl
So I replaced my code using bypassSecurityTrustResourceUrl.
4th. Credits to @dota2pro
Use *ngIf to display the image after the link was loaded. (It was edited and removed. So, I'm sorry for not showing your original contribution) Now I'm displaying in my html by testing before with
*ngIf="avatar"
Solution 2
You can statically load images from your assets folder within the Angular project. You alternatively can retrieve images statically from a back-end-point. You can overcome security in place by Angular by using bypassSecurityTrustResourceUrl
environment.ts
export const environment = {
production: false,
apiURL: 'http://localhost:8080/your-api/v1',
imageUrl: '/assets/images/yourImage',
};
component.html
<img [src]="imageUrl">
component.ts
photoUrl: SafeResourceUrl;
ngOnInit() {
this.urlService.siteProfile.subscribe(s => {
this.siteProfile = s;
if(s != null) {
this.photoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(`${this.apiUrl}/image-directory/your-pic?id`);
}
});
Solution 3
Using property binding should've worked:
<img [src]="imagePath">
but you can also try string interpolation:
<img src="{{imagePath}}">
Diego de Lima
Updated on June 04, 2022Comments
-
Diego de Lima almost 2 years
I have a path in backend side where I save my images. I can get the path from mongo and reproduce this in angular, but, when I use the tag with src bind it doesn't show the image and any errors:
The path inside the component:
this.profileService.getImg().subscribe(res => this.imagePath = res['img']);
The return of a console log:
console.log(this.imagePath); http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg
The html tag:
<img [src]="imagePath">
I've tried several ways that I found in other posts, but couldn't make it works. Any idea of what is happening and how can I solve this?
Updates and more Details
On the server side I'm returning the path from mongo by this way:
router.get('/:id', (req, res, next) => { Avatar.getAvatarById(req.params.id, (err, avatar) => { if(err) throw err; if(!avatar){ return res.json({success: false, msg: 'No avatars found'}); } res.json({ success: true, avatar: avatar }); }); });
Where Avatar.getAvatarById is:
module.exports.getAvatarById = function(id, callback){ const query = { avatar: {$regex: ".*"+id+".*" }} Avatar.findOne(query, callback); }
And I'm exposing the avatars path like that:
app.use('/avatars', express.static('avatars'));
When I try to access the path by taping http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg in the browser, it returns the json instead of render the image.
{ "success":true, "avatar": { "_id":"5dc17fc9f383424158c59754", "avatar":"http://localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg","__v":0 } }
Also tried to overcome security by using bypassSecurityTrustResourceUrl and use *ngIf to display when the url is there.
this.photoUrl = this.sanitizer.bypassSecurityTrustUrl(res['avatar']['avatar']); <img *ngIf="photoUrl" [src]="photoUrl">
It doesn't return any errors and stil doesn't display the image.
If I try by tapping the path inside
bypassSecurityTrustUrl
function to test, and remove the *ngIf, it returns:null:1 GET http://localhost:4200/null 404 (Not Found)
-
Thatkookooguy over 4 yearsHi Diego. Have you exposed the image folder as a static folder and connected it to
/avatars
? Right now you only get the image path from the backend, but you didn't do any steps to expose the content of that folder (at least from the code you shared)..
-
-
Diego de Lima over 4 yearsI've already exposed it as the same way. But will test by using res.sendFile way and return with the result
-
Diego de Lima over 4 yearsI did both but nothing happens.
-
Diego de Lima over 4 yearsTried it already. But it returns an error: GET localhost:4200/null 404 (Not Found)
-
HenryDev over 4 years@DiegodeLima Have you tried putting the image type in the URL? and check if you are able to see the image? just put this in the URl localhost:3000/avatars/5db84cdf4c6efe073864f9e7.jpeg and tell us what you see
-
Diego de Lima over 4 yearsI already did a validation with *ngIF and also tested by trying to display the content and it's returning the string with the path
-
Diego de Lima over 4 yearsTake a look at the question. I just updated it with the return when I try it
-
Diego de Lima over 4 yearsIan I did it but it returns null:1 GET localhost:4200/null 404 (Not Found). Even when I type the path manually inside the bypassSecurityTrustResourceUrl function.
-
Diego de Lima over 4 yearsTried to use res.sendFile but it didn't return any different result.