I'm a beginner programmer and I've been spending the entire week to understand how to get images from an ASP.NET Web API and display them in the browser using an Angular project, and didn't understand how to do it at all.
- ASP.NET Framework Web API 4.7
- Angular CLI: 13.3.7
- Angular: 13.3.11
Web API side:
Model class:
public class MotorTestImgDTO
{
public byte[] Image { get; set; }
}
Controller:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MotorTestImgController : ApiController
{
private NavEcommerceDBfirstEntities db = new NavEcommerceDBfirstEntities();
//Have been trying to convert the byte array to base64String but Swagger showed
//error massage. So I removed it and tried to get the images as byte[] in the
//Angular side and then tried to use Blob but too complicated for me.
private Base64StrConverter base64Str = new Base64StrConverter();
public IQueryable<MotorTestImgDTO> Get()
{
var allMotorImgs = db.Motorcycles
.Select(m => new MotorTestImgDTO
{
Image = m.Image
});
return allMotorImgs;
}
}
Angular side:
Model interface:
export interface MotorTestImage {
image: Byte[];
}
Service:
@Injectable({
providedIn: 'root'
})
export class MotorTestImgService {
imageUrl = 'https://localhost:*****/api/MotorTestImg';
constructor(private http: HttpClient) { }
getAllMotorsTestImg(): Observable<MotorTestImage[]> {
return this.http.get<MotorTestImage[]>(this.imageUrl);
}
}
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { HomePage } from './Model/home-Page.model';
import {MotorTestImage} from './Model/motor-test-img.model';
import {MotorTestImgService} from './Service/motor-test-img.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'AngularUI';
motorTestImg: MotorTestImage[] = [];
constructor(private motorTestImgService: MotorTestImgService) {}
ngOnInit(): void{
this.allMotorsImgsTest();
}
allMotorsImgsTest(){
this.motorTestImgService.getAllMotorsTestImg().subscribe(
response => {
this.motorTestImg = response;
console.log(response);
}
)
}
}
app.component.html:
<h4>{{title}}</h4>
<div *ngFor="let item of motorTestImg">
<img src="{{item.image}}" />
</div>
Outputs
Swagger:
Angular output to browser:
Devtools console:
Appreciate for your help in advance.