Uploading file without the now deprecated FileTransfer plugin

Cordova deprecated the FileTransfer plugin. So I tried to upload images taken with the Camera plugin without it. Actually uploading a file with angular’s httpClient is pretty easy. However converting a local file into a blob was all but straight forward. There is a cordova blog post, which explains how it is done.

The javascript code is however not very suitable for angular. I ended up with following code:

    private uploadFile(serverurl: string, filePath: string): Observable<boolean> {
        // convert filePath into blob. see:
        // https://cordova.apache.org/blog/2017/10/18/from-filetransfer-to-xhr2.html
        return from(this.file.resolveLocalFilesystemUrl(filePath)).pipe(
            mergeMap((fileEntry: FileEntry) => {
                // wrap callback into observable
                return Observable.create(observer => {
                    fileEntry.file(file => {
                        const name = file.name;
                        const reader = new FileReader();
                        reader.onloadend = () => {
                            const imgBlob = new Blob([reader.result], { type: file.type });
                            observer.next([imgBlob, name]);
                            observer.complete();
                        };
                        reader.readAsArrayBuffer(file);
                    }, error => {
                        observer.error(error);
                    });
                });
            }),
            mergeMap(([imgBlob, name]) => {
                const formData = new FormData();
                formData.append('file', imgBlob, name);

                return this.httpClient
                    .post(serverurl, formData).pipe(
                        map(() => true)
                    );
            })
        );
}

I post this here for anybody who needs it. If the code can be further simplified, please let me know.

A full example project is here on github: https://github.com/nharrer/ionic-file-upload

Regards,
Norbert

1 Like

Is there an download example?

In my case it does not work. onloadend is not fired, no idea why :confused: