Often in the group to see friends for a variety of easy to use plug-ins, components and so on, here I share a simple function, very practical file upload components.

For a component, it’s better to just do its job and not do something else

case



Yes, it is that simple, and this style is not in the component, here is a simple container for better demonstration.


@Component({
    selector: '[fileUpload]',
    template:` 
       
      
`
, styles:[ ` :host { cursor: pointer; } `]})export class FileUploadComponent implements OnInit { constructor(){ } ngOnInit(){ } @Input('multiple') multiple: boolean = false; @Input('disabled') disabled: boolean = false; @Input('drop') isDrop; @Output('eventChange') eventChange = new EventEmitter<any> ();@ViewChild('file') fileRef: ElementRef; @Output('eventDragleave') eventDragleave = new EventEmitter<any> ();@Output('eventDragenter') eventDragenter = new EventEmitter<any> ();@Output('eventDragover') eventDragover = new EventEmitter<any> (); change(file){this.eventChange.next(file.files) this.fileRef.nativeElement.value = null; } @HostListener('click') eventClick() { if (this.disabled) return; this.fileRef.nativeElement.click(); } @HostListener('dragleave'['$event']) dragleave(e) { e.preventDefault(); e.stopPropagation(); if (!this.isDrop) return; this.eventDragleave.next(e) } @HostListener('dragenter'['$event']) dragenter(e) { e.preventDefault(); e.stopPropagation(); if (!this.isDrop) return; this.eventDragenter.next(e) } @HostListener('dragover'['$event']) dragover(e) { e.preventDefault(); e.stopPropagation(); if (!this.isDrop) return; this.eventDragover.next(e) } @HostListener('drop'['$event']) drop(e) { e.preventDefault(); e.stopPropagation(); if (!this.isDrop) return; if (this.disabled) return; this.eventChange.next(e.dataTransfer.files); }}Copy the code


The code doesn’t have to be very complicated to accomplish a single task, and there are two ways to upload it: click and drag.

This component also addresses other requirements, such as file type verification, size verification, and image and video verification for width, height, and length.

If there is demand can imitate Baidu upload control API (Webuploader) to develop again, step by step to improve the upload control.

demo

html:
<div fileUpload (eventChange)="change($event)" [drop]="true"></div>
typescript:
change(files){
    console.info(files[0])
}Copy the code

Afterword.

Later, I will write a complex upload control based on this version. I also hope you can granulate and simplify components as much as possible, gradually improve and iterate your own components, and gradually accumulate and learn others’ writing methods, which is also a learning process.