Nativescript and resources folder - is there a simple solution?

早过忘川 提交于 2019-12-08 03:40:30

问题


I will start with the fact that currently - I'm uploading successfully an mp3 file to a server - but via a hacky way.

I'm having 2 raw folders as you can see :

And here is the working code to upload the file :

 upload1()
    {

        let file = fs.path.join(fs.knownFolders.currentApp().path, "raw/a1.mp3");

        var request = {
            url:         "http://posttestserver.com/post.php",
            method:      "POST",
            ...
        };

        var task = session.uploadFile(file, request);
        task.on("progress", this.logEvent);

    }

Here is the output for the successful upload (showing progress)

So where is the problem ?

The current file is being uploaded from the root raw folder. (proof)

But the right way (as I was told)is to upload it via the raw folder or the assets folder and then reference it via res://raw/a1.mp3 ( or res://raw/a1).

So I've switched to : let file="res://raw/a1.mp3";

But got an error:

ERROR Error: java.io.FileNotFoundException: Could not find file at path: res://raw/a1.mp3

Also for : let file="res://raw/a1"; //without extension - Got an error :

JS: ERROR Error: java.io.FileNotFoundException: Could not find file at path: res://raw/a1

Question:
How can I access the mp3 file under the raw folder? (not the outside folder but the resource one)


回答1:


I am unfamiliar with NativeScript but here is an example of how to access the raw folder files regardless of type using Java:

public static final FileDescriptor getFDForResource(Context context, int resId) {
     AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId);
     if (afd != null) {
        return afd.getFileDescriptor();
     }
     return null;
}

public void readFile(int resId) {
    FileDescriptor fd = getFDForResource(resId);
    InputStream inputStream
    if(fd != null) {
        inputStream = new FileInputStream(fd);
        byte nextByte;
        while((nextByte = inputStream.read()) != -1) {
            // Upload the file bytes to your server.
        }
    }
}

You'll wanna place this code in a Util class and access it using NativeScript. I'm sure there is some API to do such a thing but being I am unfamiliar that is all I can provide.



来源:https://stackoverflow.com/questions/47532620/nativescript-and-resources-folder-is-there-a-simple-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!