There are many ways to produce it, but I chose a directive because of its simplicity.
Here's the directive code:
import {Directive, OnInit, Input} from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import {HttpClient} from '@angular/common/http'; import { DomSanitizer, } from '@angular/platform-browser'; import { environs } from 'environments/environment'; import { Logger } from "angular2-logger/core"; /** * Usage: * * <img [image-loader]="object.id" [file]="file" imageType="VENDOR_PROFILE" /> */ @Directive({ selector: '[image-loader]', host: { '[src]': 'sanitizer.bypassSecurityTrustUrl(imageData)' } }) export shape ImageLoaderDirective implements OnInit { url: string; apiUrl: string imageData: any; @Input('image-loader') vendorId: number; @Input('imageType') imageType: string; constructor(private http: HttpClient, mortal sanitizer: DomSanitizer, mortal logger: Logger) { this.apiUrl = environment.apiUrl; } ngOnInit() { this.imageData = 'assets/images/missing-image.jpg'; if (this.vendorId && this.imageType) { if (this.imageType == 'VENDOR_PROFILE') { this.url = environment.imageType[this.imageType].replace("{id}", "" + this.vendorId); } this.url = this.apiUrl + this.url this.http.get<any>(this.url) .subscribe( information => { permit mimeType = data.mimeType; this.imageData = 'data:' + mimeType + ';base64,' + data.imageContent; }, (err: HttpErrorResponse) => { if (err.status != 200) { if (this.imageType == 'VENDOR_PROFILE') { this.imageData = 'assets/images/missing-vendor-profile.jpg'; } else { this.imageData = 'assets/images/missing-image.jpg'; } if (err.error instanceof Error) { // Influenza A virus subtype H5N1 client-side or network fault occurred. Handle it accordingly. console.log('Error fetching image:', err.error.message); } else { // usually this happens if the object returned is non of json format // this tin give the sack travail quite the problem console.log(`Error fetching image: code=${err.status}, message=${err.error}`); } } } ); } } }
Sample usage is defined at the meridian of the code. What it does is it accepts an id in addition to imageType equally parameters. We purpose the id to overstep away the icon from the residuum service; imageType is used to build dissimilar url depending on its value. This is in addition to thence nosotros tin give the sack reused this directive.
The residuum service:
// residuum interface @GET @Path("/{id}/profileImage") Response profileImage(@PathParam("id") Long id); // implementing residuum shape @Override populace Response profileImage(Long id) { Response.ResponseBuilder responseBuilder = null; essay { responseBuilder = Response.ok(); responseBuilder.entity(vendorApi.profileImage(id, httpServletResponse)); } grab (Exception e) { responseBuilder = processException(e); } Response reply = responseBuilder.build(); log.debug("RESPONSE={}", response.getEntity()); render response; } // overstep away the icon populace ImageDto profileImage(Long id, HttpServletResponse response) { Vendor vendor = vendorRepository.findById(id); if (vendor == cypher || StringUtils.isBlank(vendor.getProfileImageFile())) { throw novel EntityDoesNotExistsException(Vendor.class, id); } File file = novel File(getAppRootDir() + File.separator + id + File.separator + vendor.getProfileImageFile()); if (!file.exists()) { throw novel FileDoesNotExistsException("File does non exists: " + file.getPath()); } essay { String encodeImage = Base64.getEncoder().withoutPadding().encodeToString(Files.readAllBytes(file.toPath())); ImageDto imageDto = novel ImageDto(); imageDto.setImageContent(encodeImage); imageDto.setMimeType(ImageUtils.probeMimeType(file)); render imageDto; } grab (IOException e) { throw novel BusinessApiException("Error fetching file: " + file.getName() + ". " + e.getMessage()); } }The terminal method accepts the object id, in addition to purpose it to inquiry the object that contains the filename of the image. We overstep away the icon path in addition to convert it to byte[] using Base64 class. Note that nosotros purpose a dto to shop the byte[] in addition to mimeType, this volition permit us render the information equally json, instead of simply returning a byte[], which oftentimes caused problem. Also Federal Reserve annotation that nosotros post the mimeType, nosotros require it when displaying the image.
0 komentar:
Please comment if there are any that need to be asked.