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);
}
}
}
@rafay-abedi
Copy link

where are you getting the 'image' from in the following code: <img src="" thumbnail [image]="item?._file"/>

When I applied your code to my project it gives a template parse error saying "can't bind to image since it isn't a known property of 'img'."

you need to import directive in your module.

@venterg
Copy link

venterg commented Jul 23, 2019

@maneet13 I've imported the directive and still get the same error "can't bind to image since it isn't a known property of 'img'." @tnqsoft

@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