Search code examples
androidcordovadownloadionic4device

Save PDF to device in Ionic 4


I have this code, which can be run after device ready since it's on a secondary route. I'm working on Android at this time.

import { File } from "@ionic-native/file/ngx";
import { FileTransfer, FileTransferObject } from "@ionic-native/file-transfer/ngx";
constructor(private _transfer: FileTransfer,
                private _platform: Platform,
                private _file: File){

}

startDownload(file: XmatFile): void {
        this.docsLoading = !0;
        let path = void 0;
        let visualPath = "";
        if (this._platform.is("ios")) {
            path = this._file.documentsDirectory;
            visualPath = path;
        }
        else {
            path = this._file.externalRootDirectory + "Download/";
            visualPath = path.replace("file://", "");
        }
        this._checkPaths(path);
        const fileTransfer: FileTransferObject = this._transfer.create();
        fileTransfer.download(file.url, path + `tmp_${+new Date()}.pdf`, true, {
            "content-type": mobSfcContentTypes.pdf
        })
        .finally(() => this.docsLoading = !1)
        .then((downloadedFile) => {
            (window as any).resolveLocalFileSystemURL(path, (dir) => {
                dir.getFile(file.fileName, {create: true}, (newFile) => {
                    newFile.createWriter((fileWriter) => {
                        fileWriter.write(downloadedFile);
                        fileWriter.onwrite = () => {
                            this._snack(!0, `File scaricato in ${visualPath}`);
                        };
                    }, () => {
                        this._snack(!1, `Errore salvataggio in ${visualPath}`);
                    });
                });
            });
        }, (error) => {
            console.warn("mob-sfc-help => DOC download error", error);
            this._sfcFunctionsSrv.showErrorAlert(`Non è stato possibile scaricare il file ${file.fileName}.
            <br />Si prega di riprovare più tardi ed eventualmente aprire un ticket`);
        });

    }

I have a problem. The download goes ultra quick and saves a two files, but both are very small (a few bytes), while the target pdf is around 2MB.

Am I doing something wrong?


Solution

  • I solved it this way

    import {HTTP} from "@ionic-native/http/ngx";
    
    export class MyComponent {
    
    
    constructor(private _nativeHttp: HTTP) {
    }
    
    doDownloadToDevice(file: MyFileModel):void {
        this._spinner.show();
        this._nativeHttp.downloadFile(file.url, {}, {}, this._downloadPath)
            .finally(() => this._spinner.hide())
            .then((_r_) => {
                console.info("SUCCESS");
            }, (e) => {
                console.warn("Download error", e);
            });
    }
    

    Hope this helps.