I'm currently working with Angular 6 and I have a requirement to retrieve an image that is dropped into a div
element and assign it as the value of an input type="file"
within a form.
The process involves the user dropping an image into the designated div
, which should then be captured by the file input, allowing for form submission.
Below is the code snippet:
<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>
In addition, there is the corresponding component:
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]);
}
Despite having a value in the input.value
upon dropping, it seems to be of the incorrect type, rendering the submit button inactive.
To address this issue, consider moving the logic from the readfiles
function. The proposed code changes do not work due to an error related to result
. The specific error message is
Property result does not exist on type EventTarget
.
If you have insights on how I can resolve this and successfully set the image as the value of the file input, please share your suggestions.
Thank you for your assistance.
P.S. Here is the StackBlitz link