I am using Angular 6 and I want to get the image that is dropped in a div and set it as a value in the input type="file" of a form.
So, the user drops an image in the div, the file input gets that image as a value and then I can submit the form.
This is the code
<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>
and the component is
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]);
}
The input.value in the drop always has a value, but I guess is the wrog type of value. The submit button of the form is not active.
Then maybe I need to read the image to set it as a value, so I will transfer the logic in the readfiles - check the commented out code. This does not work, since I get an error no the result of the input.value = event.target.result; . The error is Property result does not exist on type EventTarget
How can I fix this and set the image as a file input value ?
Thanks
PS, here is the stackblitz