I'm facing an issue where the image I send from a nestjs backend to an angular frontend isn't displaying in the browser.
https://i.sstatic.net/nicu4.png
Here's how it works: I make a request from the frontend to the backend with the file path on the server (e.g., "C:\MyFolder\MyFile.png"). The backend reads the image and sends a stream back to the frontend. The frontend then converts the blob into an image and sets the src attribute of an img element to display the image.
Backend
Below is the code snippet from the controller:
@HttpCode(201)
@Get(':imageUrl')
@Header('Content-Type', 'image/png')
getFile(@Param('imageUrl')imageUrl: string) {
imageUrl = atob(imageUrl);
return fs.createReadStream(imageUrl);
}
Frontend
Here is the TypeScript code for the language selector:
currentLanguage: ApplicationLanguage;
availableLanguages: ApplicationLanguage[];
constructor(private readonly _languageProvider: CultureProviderService,
private readonly _imageLoader: ImageService) {
// Code here...
}
ngOnInit(): void {
// Code here...
}
// More code snippets here...
The service used to fetch the image is as follows:
constructor(private readonly _http: HttpClient,
private domSanitizer: DomSanitizer) { }
// Code for getImage() and createImageFromBlob() methods
The HTML section:
<div>
<mat-selection-list (selectionChange)="changeLanguage($event)"
[multiple]="false">
<mat-list-option *ngFor="let language of availableLanguages"
[value]="language" [selected] ="isSelected(language)">
<img [src]="language.image" height="70px" width="70px" alt="Flag">
</mat-list-option>
</mat-selection-list>
</div>
If you see any issues or have suggestions, please let me know!
Edit:
The solution based on the accepted answer
To resolve the issue, I needed to upgrade the nestjs version to v8+. I encountered some challenges during the update process but managed to get it working by creating a new nestjs project using CLI v8+.
I also updated the controller's code to utilize StreamableFile
as per the recommended solution:
@HttpCode(201)
@Get(':imageUrl')
@Header('Content-Type', 'image/png')
getFile(@Param('imageUrl')imageUrl: string): StreamableFile {
imageUrl = Buffer.from(imageUrl, 'base64').toString();
const file = createReadStream(imageUrl);
return new StreamableFile(file);
}
For more information, check out the official resource: https://docs.nestjs.com/techniques/streaming-files