I store created png files in the EXTERNAL folder of my ionic App using the Capacitor FileSystem Plugin
The files are correctly stored, I see them when using the device’s file explorer and I can also use them as src on img tags.
For uploading them,
I am:
- Getting the URI using Capacitor.Filesystem.getUri
- Getting the file URL with Capacitor.convertFileSrc
- Using
fetchto get the stream and convert it toArrayBuffer. - Creating a
Fileobject from theArrayBuffer. - Upload it.
The problem I am having is that the File gets created in a wrong way. For some reason, the File.name gets the ArrayBuffer as name and the type gets also an object containing the type.
Of course, after upload It is not an image anymore:
{
"name":[ArrayBuffer(12345)],
"localURL":"my-file.png",
"type":{
"type":"image/png"
},
"lastModified":null,
"lastModifiedDate":null,
"size":0,
"start":0,
"end":0
}
This is the code:
public getFile$(localFileName): Observable<File> {
this.getUri$(localFileName).pipe(
switchMap((uri) => {
const fileURL = this.capacitorService.convertFileSrc(uri);
// distinct between native and web
// https://github.com/diachedelic/capacitor-blob-writer/blob/d2a1b1188c9465e765c1be87c607da6871350eea/demo/src/index.ts#L117
if (fileURL.includes('://')) {
console.log('NATIVE');
return fetch(fileURL).then((fileResponse) => {
if (fileResponse.status === 404) {
throw new Error('File not found');
} else if (fileResponse.status !== 200) {
throw new Error('bad status');
}
return fileResponse.arrayBuffer();
});
}
console.log('WEB');
// web environment does not yet support HTTP access to files
return this.fileStorageService
.read$(localFileName)
.pipe(
switchMap((data) => {
const url = 'data:;base64,' + data;
return fetch(url);
}),
switchMap((res) => {
return res.arrayBuffer();
})
);
}),
map((arrayBuffer) => {
const file = new File([arrayBuffer], localFileName, {
type: 'image/png',
});
if (file.name !== localFileName) {
const error = 'The created file has a bad format';
console.error({ error, file });
throw new Error(error);
}
return file;
})
);
}
Any help is appreciated.