【发布时间】:2018-09-17 15:21:42
【问题描述】:
我正在使用 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
【问题讨论】:
标签: angular typescript input angular6