Skip to content

Instantly share code, notes, and snippets.

@tnqsoft
Last active June 29, 2024 14:09
Show Gist options
  • Save tnqsoft/38aed9ee97d200bb899f61e68ebb2a9d to your computer and use it in GitHub Desktop.
Save tnqsoft/38aed9ee97d200bb899f61e68ebb2a9d to your computer and use it in GitHub Desktop.
Preview image for ng2-file-upload
<div *ngFor="let item of uploader.queue; let first = first;">
<img src="" thumbnail [image]="item?._file"/>
{{ item?.file?.name }}
{{ item?.file?.size }}
</div>
<input type="file" ng2FileSelect [uploader]="uploader" #fileInput [accept]="accept.toString()" [multiple]="multiple"/>
import { Directive, ElementRef, Input, Renderer, OnChanges, SimpleChanges } from '@angular/core';
@Directive({
selector: 'img[thumbnail]'
})
export class ThumbnailDirective {
@Input() public image: any;
constructor(private el: ElementRef, private renderer: Renderer) { }
public ngOnChanges(changes: SimpleChanges) {
let reader = new FileReader();
let el = this.el;
reader.onloadend = (readerEvent) => {
let image = new Image();
image.onload = (imageEvent) => {
// Resize the image
let canvas = document.createElement('canvas');
let maxSize = 70;
let width = image.width;
let height = image.height;
if (width > height) {
if (width > maxSize) {
height *= maxSize / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width *= maxSize / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
el.nativeElement.src = canvas.toDataURL('image/jpeg');
};
image.src = reader.result;
};
if (this.image) {
return reader.readAsDataURL(this.image);
}
}
}
@matheusslg
Copy link

Line 41:
change this:
image.src = reader.result;
to this:
image.src = reader.result as string;

@rezanadimi72
Copy link

change
<img src="" thumbnail [image]="item?._file"/>
to:
<img src="" thumbnail [image]="item?.file.rawFile" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment