import {Component, OnInit, forwardRef, EventEmitter, Input} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {UploadOutput, UploadInput, UploadFile, humanizeBytes, UploaderOptions} from 'ngx-uploader'; import FileService from "@common/services/file"; @Component({ selector: 'mediaUploader', templateUrl: './template.html', styleUrls: ['./style.less'], providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MediaUploader), multi: true }] }) export default class MediaUploader implements OnInit { private onValueChange: any; uploadInput: EventEmitter = new EventEmitter(); options: UploaderOptions; //默认允许上传1张 @Input() max = 3; //默认10M @Input() size = 0.1; //附件宽度 @Input() width; //附件高度 @Input() height; //默认'jpg', 'png', 'jpeg'格式 private _type = ['JPG', 'PNG', 'JPEG', 'MP4']; @Input() set type(value) { this._type = value.split(',') }; private errorInfo = ''; private fileList = []; private uploading = false; private uploadProgress = 0; get sizeStyle() { return { 'height': '100px', 'width': (this.width && this.height ? (this.width * 100 / this.height).toFixed(0) : 100) + 'px' }; } files: UploadFile[] = []; constructor(private fileService: FileService) { } ngOnInit(): void { } writeValue(obj: any): void { if (obj) { if (obj instanceof Array) { this.fileList = obj; } else { this.fileList = []; } } else { this.fileList = []; } this.setValue(); } registerOnChange(changeFn: any): void { this.onValueChange = changeFn; } registerOnTouched(changeFn: any): void { } delImg($event, $index) { $event.stopPropagation(); if (this.fileList.splice($index, 1)[0].master && this.fileList.length > 0) { this.fileList[0].master = true; } this.setValue(); }; select(file) { this.fileList.map(item => { item.master = false; }); file.master = true; this.setValue(); } onUploadOutput(output: UploadOutput): void { if (output.type === 'allAddedToQueue') { const event: UploadInput = { type: 'uploadAll', fieldName: 'image', url: this.fileService.imageUpload() }; this.uploadInput.emit(event); } else if (output.type === 'done' && typeof output.file !== 'undefined') { if (this.fileList.length < this.max) { this.fileList.push({ master: this.fileList.length == 0, url: output.file.response.image, supportVideo: output.file.type == 'video/mp4' }); } this.setValue(); } } setValue() { this.onValueChange && this.onValueChange(this.fileList); } }