Reputation: 707
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
Upvotes: 3
Views: 14875
Reputation: 2566
what do you want to find as value in the imageInput formControl ?
A way to make it work is to change input.value to
input.setValue(e.dataTransfer.files[0]);
Like this the formControl will be correctly up to date and not INVALID anymore... BUT since you use an input file it will not work (it will tell you that he want a fileName)
But actually you don't really use the input file as an input file so you can change the input in the HTML by removing the type="file" and your form should work ;)
here you could find a image chooser of my own working with ngModel or formControlName and which can be init with base 64 : https://github.com/xrobert35/asi-ngtools/tree/angular6-compatibility/src/components/asi-image-chooser and a working demo here : https://ng-tools.asi.fr/views/showroom/asi-ngtools/components/asi-image-chooser
Upvotes: 2