gpt4 book ai didi

html - Angular 5 文件上传 : Failed to set the 'value' property on 'HTMLInputElement'

转载 作者:太空狗 更新时间:2023-10-29 13:45:11 24 4
gpt4 key购买 nike

我有一个用于在 angular 5 应用程序中上传文件的表单,因为我已经从我前一段时间编写的代码中完全复制了它,所以我可以发誓它以前工作过。

这是我的 HTML 代码:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-group">
<label>File:</label>
<input #theFile type="file" (change)="onFileChange($event)" accept=".png" class="form-control"
formControlName="content" />
<input type="hidden" name="fileHidden" formControlName="imageInput"/>

<!-- [(ngModel)]="model.content" -->

<div class="alert alert-danger" *ngIf="!form.prestine && form.controls.content.errors?.noFile">
Please provide a photo.
</div>
<div class="alert alert-danger" *ngIf="form.controls.content.errors?.fileTooBig">
The file is too big and won't uploaded. Maximum allowed size is 500kb.
</div>
</div>
<div class="form-group">
<label>Notes</label>
<textarea type="text" class="form-control" formControlName="notes" [(ngModel)]="model.notes" > </textarea>
</div>
<button type="submit" class="btn btn-primary" [disabled]="!form.valid">Submit</button>
<button class="btn btn-default" type="button" (click)="close(false);">Cancel</button>
</form>

这里是 fileUpload 控件中使用的“onFileChange”方法:

onFileChange($event)
{
if ($event.target.files.length > 0)
{
let ftu: File = null;
ftu = $event.target.files[0];
this.form.controls['content'].setValue(ftu);
this.model.content = $event.target.files[0];
}
}

这是我编写和使用的自定义验证器的代码:

import { FormControl } from '@angular/forms';

export class SekaniRootImageValidators
{
static sizeTooBig(control: FormControl)
{
if (!control.value)
{
return { noFile : true }
}
else if (control.value[0].size > 505000)
{
return { fileTooBig: true}
}
return null;

}
}

现在的问题是,只要我在输入控件中选择一个文件,我就会在控制台中收到此错误消息:

ERROR DOMException: Failed to set the 'value' property on'HTMLInputElement': This input element accepts a filename, which mayonly be programmatically set to the empty string.

此代码以前有效,所以我什至不知道从哪里开始。感谢您的帮助!

注意:这是有效答案的链接:Angular2: validation for <input type="file"/> won't trigger when changing the file to upload

最佳答案

在我的例子中,我只是删除了 formControlName:

<input type="file" (change)="onFileChange($event)">

和.ts:

onFileChange(event) {
const reader = new FileReader();

if (event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.data.parentForm.patchValue({
tso: reader.result
});

// need to run CD since file load runs outside of zone
this.cd.markForCheck();
};
}
}

关于html - Angular 5 文件上传 : Failed to set the 'value' property on 'HTMLInputElement' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49970970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com