I use the following code to upload a file in Angular:
HTML
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="uploadRenewals($event.target.files)">
</div>
Typescript
fileToUpload: File = null;
uploadRenewals(files: FileList) {
console.log('Uploading starts...', files);
const formData: FormData = new FormData();
this.fileToUpload = files.item(0);
formData.append('file', this.fileToUpload, this.fileToUpload.name);
this._docService.uploadRenewals(formData)
.pipe(take(1))
.subscribe((response: RenewalsResponse) => {
console.log('Response is', response);
}, (error) => {console.log(error);});
Service
uploadRenewals(formData: FormData) {
return this._http.post(this.baseUrl + '/docs/uploadRenewals', formData, { responseType: 'json' })
.catch(this.errorHandler);
}
The thing here is that it works when I upload different file each time, but when I try to upload the same file nothing is triggered and the uploadRenewals() function is never called.
Also I noticed that when I open the window (change)="uploadRenewals($event.target.files) the third time (after I chose the same file the 2nd time and nothing happened) and close it without selecting any file, the uploadRenewals() is called and in console is showed the below error:
ERROR TypeError: Cannot read property 'name' of null
Any idea what is happening and how to fix this?