我正在使用 Angular 6,我想获取放在 div
中的图像,并将其设置为 input type="file"
中的值表单。
因此,用户在 div
中放置了一张图片,文件输入获取该图片作为值,然后我可以提交表单。
这是代码
<form [formGroup]="imageUpload" (ngSubmit)="imageUploadSubmitted()">
<div id="imageDrop" (drop)="drop($event)" (dragover)="allowDrop($event)" #imageDrop></div>
<input type="file" formControlName="imageInput" required #imageInput id="imageInput" >
<label>
<input type="text" formControlName="imageName" placeholder="name" required >
</label>
<button type="submit" [disabled]="!imageUpload.valid">Submit</button>
</form>
组件是
allowDrop(e) {
e.preventDefault();
}
drop(e) {
e.preventDefault();
this.imageUpload.controls.imageInput.reset();
this.imageDrop.innerHTML="";
let input = this.imageUpload.controls.imageInput as any;
input.value = e.dataTransfer.files[0];
this.readfiles(e.dataTransfer.files);
}
readfiles(files){
const reader = new FileReader();
let image = new Image();
reader.onload = (event) =>{
this.imageDrop.nativeElement.innerHTML="";
let fileReader = event.target as FileReader;
image.src = fileReader.result;
image.width = 150;
this.imageDrop.nativeElement.appendChild(image);
/*if (this.imageUpload.controls.imageInput.value==null) {
let input = this.imageUpload.controls.imageInput as any;
input.value = event.target.result;
} */
};
reader.readAsDataURL(files[0]);
}
drop
中的input.value
总是有一个值,但我猜是 wrog 类型的值。表单的提交按钮未激活。
然后也许我需要读取图像以将其设置为一个值,所以我将在 readfiles
中传输逻辑 - 检查注释掉的代码。这不起作用,因为我得到的错误不是 input.value = event.target.result;
的 result
。错误是 Property result does not exist on type EventTarget
如何解决这个问题并将图像设置为文件输入值?
谢谢
PS,这里是stackblitz
最佳答案
您想在 imageInput formControl 中找到什么值?
使其工作的一种方法是将 input.value 更改为
input.setValue(e.dataTransfer.files[0]);
像这样 formControl 将正确地更新并且不再无效......但是因为你使用输入文件它不会工作(它会告诉你他想要一个文件名)
但实际上您并没有真正将输入文件用作输入文件,因此您可以通过删除 type="file"来更改 HTML 中的输入,并且您的表单应该可以工作;)
在这里你可以找到我自己使用 ngModel 或 formControlName 的图像选择器,它可以用 base 64 初始化: https://github.com/xrobert35/asi-ngtools/tree/angular6-compatibility/src/components/asi-image-chooser 和一个工作演示在这里: https://ng-tools.asi.fr/views/showroom/asi-ngtools/components/asi-image-chooser
关于angular - 在 Angular 6 中设置文件输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52371040/