TomG
TomG

Reputation: 538

Save POST response as file in NativeScript

In my NativeScript-Vue app, I make a POST request to my server and receive a binary file. It's a .zip file containing a .db file which I want to copy and initialize with the nativescript-sqlite plugin.

I am using axios and the POST response looks like this:

"PK  {[oP'g�R     606.db�}`�����ו�N�-{�*�*�O炵W$�滓\(��t�KZ��dc2�e�C�Ĕ$�L
>b!��... and so on

Right now I am testing on Android. I am saving the file to the Android Downloads folder to see if I can unzip it. I know that File.write accepts a native byte array, so I am trying to get one from the binary file string.

import * as fs from "tns-core-modules/file-system";

async function saveToFile(binary) { // binary = "PK  {[oP'g�R...

    let folder = fs.Folder.fromPath(android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
    let zipFile = folder.getFile("Database.zip");

    // string to buffer
    let buffer = new ArrayBuffer(binary.length);
    let view = new Uint8Array(buffer);
    for (let i = 0; i < view.length; i++) {
        view[i] = binary.charCodeAt(i);
    }

    // buffer to native byte array
    let array = Array.create("byte", view.byteLength);
    for (let i = 0; i < view.byteLength; i++) {
        array[i] = new java.lang.Byte(view[i]);
    }

    await zipFile.write(array);
}

I think I am doing things wrong, cycling arrays two times, anyway I am able to write the file but I can't open it as a .zip. Any help?

Upvotes: 1

Views: 610

Answers (1)

TomG
TomG

Reputation: 538

Solved switching from axios to NativeScript HTTP module, handling directly a File object instead of a string.

import { getFile } from "tns-core-modules/http";
import { Zip } from "nativescript-zip";

async function saveDatabaseToFile() {
    let folder = fs.knownFolders.temp();

    let zipFile = await getFile({
        method: "POST", // url, headers, content
    });
    await file.rename("Database.zip"); // extension was messed up

    await Zip.unzip({
        archive: file.path,
        directory: folder.path
    });

    let files = await folder.getEntities();
    let dbFile = files.find(file => file._extension === ".db");

    return dbFile;
}

Upvotes: 0

Related Questions