I have an read file functionality that is implemented like:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import * as Papa from 'papaparse';
@Injectable({
providedIn: 'root'
})
export class FileReaderService {
constructor() {}
// NOTE: the file-reader service currently only supports JSON and CSV files
read<T = unknown>(file: File) {
return new Observable<T>(observer => {
const fileReader = new FileReader();
fileReader.onload = () => {
try {
if (file.type === 'text/csv') {
const jsonFile = this.csvToJson(fileReader.result as string);
observer.next(jsonFile);
} else {
observer.next(JSON.parse(fileReader.result as string));
}
observer.complete();
} catch (e) {
observer.error(e);
}
};
fileReader.onerror = event => {
observer.error(event);
};
fileReader.readAsText(file);
});
}
private csvToJson(fileReader: string): any {
return Papa.parse(fileReader, {
header: true,
skipEmptyLines: true
}).data;
}
}
This file read functionality is called by an upload file functionality such as
private uploadFile(selectedFile: File) {
this.ref.data.uploadService
.upload(this.ref.data.entityGuid, selectedFile)
.pipe(
tap(progressEvent => this.handleUploadProgress(progressEvent)),
skipWhile(progressEvent => !this.isUploadComplete(progressEvent)),
delay(this.uploadDelay),
finalize(() => this.cdr.detectChanges())
)
.subscribe({
next: event => {
this.handleUploadNextEvent(event);
this.mixpanelService.sendSuccessEventMixpanel(
ExperienceFeature.BULK_MAINTENANCE_UPLOAD,
this.ref.data.name,
this.ref.data.entityGuid,
this.ref.data.entityName
);
},
error: error => {
this.handleUploadError(error);
this.mixpanelService.sendErrorEventMixpanel(
error,
this.ref.data.name,
this.ref.data.entityGuid,
ExperienceFeature.BULK_MAINTENANCE_UPLOAD,
this.ref.data.entityName
);
}
});
}
I am able to upload and read the file as expected but the problem is when I try to first upload a file this works as expected but when I try to modify and edit the same file and save it while this file is opened (such as a csv spreadsheet) and upload this changed file then I get the error of
"The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired."
I am using the FileReader API to read and upload file. I think what I need to implement is some kind of cleanup to ensure that the file handler is currently not being used by another file since this issue only happens when I want to upload the same file after I try to edit and save this opened file before uploading.