输入框黏贴或者拖拽上传文件
<textarea #enterTextarea nz-input [placeholder]="placeholder" [(ngModel)]="content"
(ngModelChange)="onContentChange($event)" [nzAutosize]="{ minRows:minRows, maxRows:maxRows }" (keydown)="handleKeyDown($event)" (paste)="pasteFn($event)"></textarea>
ts
// 限制文件类型
public accept: string = 'application/pdf,image/*,application/msword,text/plain,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document';
// 键盘按下的操作
public handleKeyDown(event: KeyboardEvent): void {
if (!this.content || !this.content.trim()) {
return;
}
event.stopPropagation();
if (event.ctrlKey && event.key === 'Enter') {
// 提交数据的操作
this.content = null;
}
}
// 添加删除class颜色
public toggleColor(bool: boolean): void {
bool ? this.renderer.addClass(this.enterTextareaRef.nativeElement, 'textarea-class')
: this.renderer.removeClass(this.enterTextareaRef.nativeElement, 'textarea-class');
}
// 清除默认行为和添加删除class
public defaultEventFn(evt: any, bool: boolean): void {
evt.preventDefault();
evt.stopPropagation();
this.toggleColor(bool);
}
public emitFile(files: Array<File>): void {
if (files.length > 0) {
if (files.some(val => !decideAccept(this.accept, val))) {
this.message.error('上传文件格式不合法');
return;
}
// 提交文件的操作
}
}
// ctrl+v 提交文件的事件
public pasteFn(event: ClipboardEvent): void {
const items: any = event.clipboardData && event.clipboardData.items;
const files: Array<File> = [];
if (items && items.length) {
for (let i: number = 0; i < items.length; i++) {
// 为什么加这个判断, 因为不用拦截文本的复制黏贴事件, 让它走默认行为
if (items[i].type !== 'text/plain') {
const fileItem: any = items[i]?.getAsFile();
if (fromCore.isImage(items[i].type)) {
fileItem.thumbUrl = this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(fileItem)) as string;
}
// 避免会出现空的情况
if (fileItem != null) {
files.push(fileItem);
}
event.preventDefault();
event.stopPropagation();
}
}
}
this.emitFile(files);
}
// 进入拖拽位置
@HostListener('dragenter', [ '$event' ])
public dragenterFn(evt: DragEvent): void {
this.defaultEventFn(evt, true);
this.dragBool = true;
}
// 离开到拖拽位置
@HostListener('dragleave', [ '$event' ])
public dragLeaveFn(evt: DragEvent): void {
this.defaultEventFn(evt, false);
this.dragBool = false;
}
// 进入拖拽的位置松开鼠标开始上传
@HostListener('drop', [ '$event' ])
public dropFn(evt: DragEvent): void {
if (!this.dragBool) {
return;
}
this.defaultEventFn(evt, false);
const files: Array<any> = Array.from(evt.dataTransfer?.files);
for (let i: number = 0; i < files.length; i++) {
if (fromCore.isImage(files[i].type)) {
files[i].thumbUrl = this.domSanitizer.bypassSecurityTrustUrl(URL.createObjectURL(files[i])) as string;
}
}
this.emitFile(files);
}
决定自己的高度的是你的态度,而不是你的才能
记得我们是终身初学者和学习者
总有一天我也能成为大佬
![](https://images.cnblogs.com/cnblogs_com/fangdongdemao/1475032/o_230710154042_qrcode_1689001024311.jpg)