我有一个ngform,其中包含一个单独的组件来上传文件。当我尝试在此组件中输入文件时,浏览器会抛出此错误:
我不明白这可能来自哪里,这是我的父html:
<form
novalidate
#logosForm="ngForm"
(ngSubmit)="brandingService.setLogos(logosForm.value)">
<div class="columns">
<div class="column">
<app-file-upload
title="Logo principal"
name="logo"
label="Logo.png">
</app-file-upload>
</div>
</div>
这是我的孩子嵌套的html(app-file-upload):
<div class="upload">
<span class="upload__label" [translate]="title"></span>
<div class="file is-fullwidth">
<label class="file-label">
<input
class="file-input"
type="file"
accept=".png, .jpg, .ico"
[name]="name"
(change)='handleFileInput($event)'
[(ngModel)]="file">
<span class="file-cta">
<span class="file-icon">
<i class="fas fa-upload"></i>
</span>
</span>
<span class="file-name">
{{label}}
</span>
</label>
</div>
<figure *ngIf="file" class="image previsualisation" [ngClass]="{'is-128x128': name == 'logo', 'is-48x48': name == 'favicon'}">
<img [src]="file">
</figure>
</div>
这是孩子的ts:
export class FileUploadComponent {
file: string | ArrayBuffer;
@Input()
title: string;
@Input()
name: string;
@Input()
label: string;
constructor() { }
handleFileInput(event: Event): void {
const userFile: File = (<HTMLInputElement> event.target).files[0];
if (userFile) {
this.label = userFile.name;
const reader: FileReader = new FileReader();
reader.onload = ((e: Event): void => {
const filereader: FileReader = <FileReader> e.target;
this.file = filereader.result;
});
reader.readAsDataURL((<HTMLInputElement> event.target).files[0]);
}
}
}
据我所知,错误可能来自于我尝试绑定文件对象(或字符串| ArrayBuffer),因此我尝试更改此对象的值,这是禁止的。我不知道如何以不同方式使用ngModel来让子组件输出用户上传的文件。如果您有任何想法,请帮助我,谢谢!
虽然我没有立即在代码中看到错误,但文件输入字段与NgModel结合显示了一些非常奇怪的行为。
Ben Nadel最近写了一篇关于如何使用ControlValueAccessor正确访问文件输入值属性的文章,也许你可以使用adopt his method instead。
我建议你按照这个链接。使用这种方式上传文件,避免重复文件,最大大小。
/* Add application styles & imports to this file! */
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.min.css')
<div>
<label class="btn btn-primary">
Upload Documents <input type="file" #fileUpload (change)="fileChangeEvent($event)" onclick="this.value=null" multiple hidden style="display:none;">
</label>
</div>
<ul>
<li *ngFor="let fileName of selectedFileNames">{{fileName}} <button (click)="removeFile (fileName)" style="cursor: pointer;"><i class="fa fa-times"></i></button>
</li>
</ul>
// Typescript代码:对于Typescript代码,请参阅