Reputation: 561
In the form of a data record, I upload a picture, the image will be uploaded to a server folder and its name will be stored in the database.
in this editing form i get the file name from server and i need to fill <input type="file">
in this form . using the reactive form in angular6 .
this is my code in ts file :
ngOnInit() {
this.EditForm=this.fb.group({
imageName:['',Validators.compose([Validators.required])]
})
this.SetForm(this.dat)
}
SetForm(dt:data){
this.EditForm.setValue({imageName:[dt.imageName]});
}
in html :
<form [formGroup]="EditForm">
<input type="file" #file formControlName="imageName">
</form>
and this is my code : stackblitz
i not idea for this problem , and i have 3 days have problem , please see my code and change that for solve this problem .
Upvotes: 4
Views: 35032
Reputation: 19
For those using ReactJs, remove the value field from the file input control to resolve the issue.
Upvotes: -1
Reputation: 1137
remove formControlName="image" and replace it with (change)="onChangeImage()"
Upvotes: 2
Reputation: 157
This works for me;
changeFileName() {
const inputElement: HTMLInputElement = document.getElementById('my-input') as HTMLInputElement
inputElement.files = null;
}
Upvotes: 1
Reputation: 3439
For security reasons, it's possible to set programmatically only an empty string to a file input value to clear the selection. If you set a value to input with type file, you'll get an error like:
ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement':
This input element accepts a filename, which may only be programmatically set
to the empty string.
As a workaround for modern browsers, DataTransfer
might be used for changing file input value:
HTML (based on stackblitz):
<form [formGroup]="EditForm">
<input id="my-input" type="file">
</form>
<button (click)="changeFileName()">Change File Name</button>
Component:
changeFileName() {
const dataTransfer = new ClipboardEvent('').clipboardData || new DataTransfer();
dataTransfer.items.add(new File(['my-file'], 'new-file-name'));
const inputElement: HTMLInputElement = document.getElementById('my-input') as HTMLInputElement
inputElement.files = dataTransfer.files;
}
Upvotes: 3
Reputation: 42516
You can rename your image file with this trick:
On your component.html, you add the event listener to listen to change
:
<input type="file" (change)="onFileChange($event)" #file formControlName="imageName">
And on your component.ts, this will create a new file with the updated file name
onFileChange(event) {
//console.log(event.target.files[0].name)
var blob = event.target.files[0].slice(0, event.target.files[0].size, 'image/png');
const newFile = new File([blob], this.dat.imageName, {type: 'image/png'})
//console.log(newFile)
}
This maintains the original file name on input
, but you can use newFile
in your post
/put
request to be sent to the backend.
Upvotes: 1