how to display images from nestjs server to Angular - html

When I upload a product from Angular side, It Post the product with imagepath, and the image is getting stored in the NestJs folder also, but I can not display product with it's image. The product is displaying at frontend but without it's image that is referenced and saved at the backend.
Anguar FrontEnd Code .ts
export class BooksComponent implements OnInit {
BookForm = new FormGroup({
_id: new FormControl(''),
name: new FormControl(''),
author: new FormControl(''),
price: new FormControl(''),
genres_name: new FormControl(''),
coverimage: new FormControl(''),
});
results?: Book[] = [];
searchedText: string = '';
constructor(
private readonly apiService: ApiService,
private router: Router
) {}
ngOnInit() {
this.apiService.getallbooks().subscribe((data) => {
this.results = data;
console.log(this.results);
});
}
Frontend html code.I'm getting all the information but not the image, here I'm providing src in img tag to display images
<div class="grid" *ngFor="let result of results">
<div class="blog-card spring-fever" style="padding: 0.5rem; z-index: 100">
<img
class="image"
src="http://localhost:3000/{{ result.coverimage }}"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
This is the information of the Product that is coming from the backend
And when I try like this src="{{result.coverimage}}" or [src]="result.coverimage" I got error localhost:4200/assets/imagename not found(404). well that is obvoius!. because there is not such path, 4200 is for Angular. but I'm uploading the images at the backend assets folder which is located at localhost:3000/assets/, and we always upload files to backend for dynamic approach from database

In your highlighted part of your post you ask how to display the image, i.e you suspect the problem is in the frontend. However there is a missing part from the provided context. In the line where the html magic happens (The img tag src attribute).
There you are string interpolating a property called coverimage under the results object. We do not see what is inside the coverimage from your backend response in the frontend screenshot. If it is an id of a document then it will not be parsed correctly. The src attribute accepts:
APNG, AVIF, GIF, JPEG, PNG, SVG, and WebP. Or base64 (which seems not the case here).
When you have the image with one of the acceptable supported formats as stated in MDN correct you can map the property to the src attribute either via
1- string interpolation:
<img src="{{imagePath}}" />
2- property binding:
<img [src]="imagePath" />
The second way is more popular, but both work fine.
PS: it is a best practice and accessibility recommended to populate the alt="" property

If you are struggling to display the images coming from server, like I was, or you are struggling with the data that is coming NestJs. Then this might work for you as it worked for me.
So in my case I had a list of books and each book has path for its image. I was using ngFor and set the image src with the path. That is the right way. But the images were not visible and Network was showing images as text/html type. The actual issue here was not the type,the actual issue was in my URL.I had a folder in NestJs server by the name of assets,that is preset at root, and I had set the path for the images(in NestJs file upload code), like this ./assets/. That is also the correct way to set the destination folder.I was able to see the images at browser like this http://localhost:3000/imagename.png,and that means my server configured to server/serve my images over root URL that's why I can access them http://localhost:3000/imagename.png. But my api was returning images in a format that contains ./assets/ in the URL.
So with the following code
<div *ngIf="result.coverimage">
<img
class="image"
src="http://localhost:3000/{{ result.coverimage }}"
alt=""
height="400px"
width="250px"
style="border: 1px solid red"
/>
</div>
I am assuming that I'm hitting the Url like this http:localhost:3000/imagename.png. But actually Angular was seeing the URL like this http:localhost:3000/./assets/imagename.png. And this is note the correct URL Format. Urls don't work with . or ,.Also becasue my server is configured at root, this urlhttp;//localhost:3000/assets/imagename.png is also wrong.And root means that, whatever the thing is set at root, that is directly access able after your server's port number. Example http://localhost:YourServerPortNumber/TheThing_Set_at_Root.
So the solution for this issue is the following
src="http://localhost:3000/{{
result.coverimage.replace('./assets/', '')
}}"
With above .replace('./assets/', '') we are removing the ./assets/ and repalcing it with '' empty space. So now URL is in this formathttp://localhost:3000/imagename.png.

Related

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.

Upload, edit and replace the existing file image in html and angular 4

I am quite new to Angular. My exact problem statement is -
I want to show a default image. If i click on the image, File selector window should open. When i select an image, i should be able to see and edit the image and finally this image should override the default image and also send this image to an API and display existing profile image if any. I want to do all this using HTML and Angular 4.
Please point me to any link if a solution to this problem already exists.
I have just been able to open the file selector till now by doing this -
<div>
<ion-input type="file" style="display: none" ngModel (change)="getFiles($event)"></ion-input>
<img src="assets/imgs/uploadImage.png" class="form-control" style="width : 20% ; height : 15%" (click)="selectFile()">
</div>
and
selectFile(): void {
let element: HTMLElement = document.querySelector('input[type="file"]') as HTMLElement;
element.click();
}
public async getFiles(event) {
console.log(event.target.files);
}
To show the profile image again, it's depend on how is the api server store your image? what is the format in that api server send an image to you, binary, cloud url...?
But for choose file and send it to server you can take a look this post...
https://www.academind.com/learn/angular/snippets/angular-image-upload-made-easy/

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

How to load image (and other assets) in Angular an project?

I'm pretty new to Angular so I'm not sure the best practice to do this.
I used angular-cli and ng new some-project to generate a new app.
In it created an "images" folder in the "assets" folder, so now my images folder is src/assets/images
In app.component.html (which is the root of my application), I put
<img class="img-responsive" src="assets/images/myimage.png">
When I do ng serve to view my web application, the image does not display.
What is the best practice to load up images in an Angular application?
EDIT: See answer below. My actual image name was using spaces, which Angular did not like. When I removed the spaces in the file name, the image displayed correctly.
In my project I am using the following syntax in my app.component.html:
<img src="/assets/img/1.jpg" alt="image">
or
<img src='http://mruanova.com/img/1.jpg' alt='image'>
use [src] as a template expression when you are binding a property using interpolation:
<img [src]="imagePath" />
is the same as:
<img src={{imagePath}} />
Source: how to bind img src in angular 2 in ngFor?
I fixed it. My actual image file name had spaces in it, and for whatever reason Angular did not like that. When I removed the spaces from my file name, assets/images/myimage.png worked.
Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes.
For example :
'my-image-name.png' should be 'myImageName.png'
'my image name.png' should be 'myImageName.png'
If you put the image in the assets/img folder, then this line of code should work in your templates :
<img alt="My image name" src="./assets/img/myImageName.png">
If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.
Being specific to Angular2 to 5, we can bind image path using property binding as below. Image path is enclosed by the single quotation marks.
Sample example
<img [src]="'assets/img/klogo.png'" alt="image">
Normally "app" is the root of your application -- have you tried app/path/to/assets/img.png?
1 . Add this line on top in component.
declare var require: any
2 . add this line in your component class.
imgname= require("../images/imgname.png");
add this 'imgname' in img src tag on html page.
<img src={{imgname}} alt="">
You can follow the below steps in Angular 8+
Step 1: load the image as below in component
const logo = require('../assets/logo.svg').default as string;
#Component({
selector: 'app-show-image',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class ShowImageComponent implements OnInit {
logo = logo;
constructor() { }
ngOnInit() { }
}
step 2: Add the logic in html file
<img [src]="logo" [alt]="'logo'">
If launched without further configuration, you will see a strange error:
ERROR in src/app/app.component.ts(4,14): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i #types/node` and then add `node` to the types field in your tsconfig.
Do as suggested – add the #types/node typings to your project by running npm install #types/node and edit tsconfig.app.json to set:
"compilerOptions": {
"types": ["node"],
...
}
For more info
resource
It is always dependent on where is your html file that refers to the path of the static resource (in this case the image).
Example A:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yourpage.html
As you can see, yourpage.html is one folder away from the root (src folder), for this reason it needs one amount of ../ to go back to the root then you can walk to the image from root:
<img class="img-responsive" src="../assests/images/myimage.png">
Example B:
src
|__assests
|__images
|__myimage.png
|__yourmodule
|__yoursubmodule
|__yourpage.html
Here you have to go u in the tree by 2 folders:
<img class="img-responsive" src="../../assests/images/myimage.png">
for me "I" was capital in "Images". which also angular-cli didn't like. so it is also case sensitive.
Some web servers like IIS don't have problem with that, if angular application is hosted in IIS, case sensitive is not a problem.
Try not give space while loading the images.
Instead of
<img src='assets/img/myimage.png' alt="">
try with string interpolation or Property Binding to load the source image as best practice.

ASP.NET MVC Img tag not loading image when loading path from database

I am attempting to make a photo gallery asp.net MVC website, and part of that involves the setting of the src to a local folder that contains images.
#model MyProj.Models.PhotoIndexViewModel
<div class="row" id="tableSearch">
#foreach (MyProj.Models.VideoModel photo in Model.PImgList)
{
<div class="col-sm-3 thumbnail">
#Html.DisplayFor(model => photo.Title)
<a href=#Url.Action("View", new { id = photo.Id })>
<img class="img-responsive"src="#Url.Content(photo.ThumbNailPrev)" alt=#photo.Id /></a>
#Html.HiddenFor(m => m.searchTerm)
#Html.Partial("_Tags", photo)
</div>
}
</div>
The ThumbNailPrev is "~/Pics/.jpg", which relates to a folder in the main part of the project. The issue is that the image does not appear. When I check the image using inspector is says it isn't found at /Pics/(photoid)/jpg. I don't understand why it is doing this, as my pics and the image itself are present at that location. I have also made sure to include the folder in my project, but it still doesn't seem to find the image.
UPDATE:
I just tried something and confirmed it is something to do with the way I'm calling the path from the database. As if I hard code the EXACT same string as the one in the database it works. The question now is why does that work?
For want of a letter..
I finally determined the problem, and it was a pretty dumb one. In code I am saving a jpEg image, but calling it via jpg. After changing the .jpg to .jpeg in the view everything works... If you are having a similar problem, check and make certain the file extension is correct.