Reputation: 580
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?
Upvotes: 0
Views: 748
Reputation: 2288
What you need is to clear the input file Element after each upload and for the second problem if you close the dialog and the event (change) fired with an empty event then when it comes to this line:
formData.append('file', this.fileToUpload, this.fileToUpload.name);
this.fileToUpload is empty.
TS :
import {
Component,
OnInit,
ViewChild,
ElementRef
} from '@angular/core';
@ViewChild('fileInput', {
static: false
}) fileInput: ElementRef;
fileToUpload: File = null;
uploadRenewals(files: FileList) {
console.log('Uploading starts...', files);
const formData: FormData = new FormData();
this.fileToUpload = files.item(0);
if (this.fileToUpload) { // this condition to avoid your the error that you mentioned
formData.append('file', this.fileToUpload, this.fileToUpload.name);
this._docService.uploadRenewals(formData)
.pipe(take(1))
.subscribe((response: RenewalsResponse) => {
console.log('Response is', response);
this.fileInput.nativeElement.value = null; //this clears the input file to let the event (change) fire again so you can upload the same file again
}, (error) => {
console.log(error);
});
}
}
HTML :
<div class="form-group">
<label for="file">Choose File</label>
<input #fileInput type="file"
id="file"
(change)="uploadRenewals($event.target.files)">
</div>
Upvotes: 2