【问题标题】:Nativescript: How to save a file in external storage (SD card)Nativescript:如何将文件保存在外部存储(SD卡)中
【发布时间】:2018-04-15 04:07:49
【问题描述】:

经过大量谷歌搜索,并多次尝试使用“脱离上下文”的代码,我请求您帮助我。

我正在尝试确定是否可以使用 Nativescript 在外部存储上进行写入。我没有兴趣在应用程序上下文中编写。所以文档显示的不是我想要的。

我已经通过 Nativescript 论坛上的一个帖子成功实现了这一点:

android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString();

它有效,它给了我一条路径,但是当我有这条路径时,我不知道如何处理它。如何在该路径中创建文件、读取文件等。

我需要实现的是创建一个用户和应用程序都可以轻松访问的文件夹。用户应该能够使用内置文件资源管理器访问此文件夹。

应用程序在 Angular 上运行。

【问题讨论】:

标签: android nativescript sd-card


【解决方案1】:

您知道您的外部(SD 卡)路径吗? 如果它像 /storage/emulated/0,那么你可以尝试这个来创建一个文件夹或文件。

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

  let externalPath= fs.path.join(android.os.Environment.getExternalStorageDirectory().getAbsolutePath().toString());
  //Create a folder with known path
  var folder: fs.Folder = fs.Folder.fromPath(sdCardPath+"/test");
  //Create a file 
  var testFile: fs.File = folder.getFile("test.txt");
  console.log("Path " + folder.path)

用户应该能够访问此折叠和文件。它位于设备内部存储中,即“外部”文件夹。

我仍在尝试弄清楚如何访问 sd 卡,但希望上面的代码对你有用。

【讨论】:

    【解决方案2】:

    我真的在 Android 设备上遇到了这个问题,最后是因为:

    1. 不确定用户在应用中是否授予了所需的权限
    2. 在我的 Macbook 上使用“Android 文件传输”来验证文件是否已创建并下载它们

    tns 信息

    nativescript 6.0.3
    tns-core-modules 6.0.7
    tns-android 6.0.2 
    

    tns 插件

    nativescript-permissions 1.3.7
    

    示例代码

            import * as fs from "tns-core-modules/file-system"
    
            ...
    
            // First get the required permissions
            // Note: this permissions should also be in your AndroidManifest.xml file as:
            //   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
            const permissions = require('nativescript-permissions')
            permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            .then(() => {
                console.log('Required Android permissions have been granted');
            })
            .catch(() => {
                console.error('Required Android permissions have been denied!');
            });
    
            // Get the publicly accessable Downloads directory path
            const sdDownloadPath = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).toString()
            console.log('sdDownloadPath: ' + sdDownloadPath)
    
            // Get a specific folder in that path (will be created if it does not exist)
            const myAppFolder = fs.Folder.fromPath(fs.path.join(sdDownloadPath, 'myApp'))
            console.log('myApp path: ' + myAppFolder.path)
    
            // Get a file in that path (will be created if it does not exist)
            // Note: In this case we try to get a unique file every time this code is run
            let date = new Date()
            date = date.toISOString().replace('.', '')
            const myFile = myAppFolder.getFile(`myfile_${date}.txt`) 
            console.log('myFile path: ' + myFile.path)
    
            // Write some data to this new file
            myFile.writeText('Hello duder 123')
            .then(() => {})
            .catch((err) => console.log(`Error writing to file: ${err}`))
    
            // Try and read back the data that was written
            myFile.readText()
            .then((res) => {
                console.log(`Text read back: ${res}`)
            }).catch((err) => {
                console.log(err.stack);
            });
    
            // List all files in the myApp folder
            myAppFolder.getEntities()
            .then((entities) => {
                // entities is array with the document's files and folders.
                entities.forEach((entity) => {
                    console.log(entity)
                });
            }).catch((err) => {
                console.log(err.stack);
            });
    

    android 文件传输问题

    我浪费了很多时间的一个问题是我可以看到带有getEntities() 的文件,但在 Mac 上使用第 3 方工具“Android 文件传输 (AFT)”时看不到它们。我最终偶然发现了“Android Studio's -> Device File Explorer”,可以看到我创建的所有文件和文件夹,因此意识到问题出在 AFT 上。

    我现在使用Airdroid 来浏览和下载设备文件。

    适用参考

    https://docs.nativescript.org/angular/ng-framework-modules/file-system (角度文档,但也与 nativescript-vue 相关)

    【讨论】:

      【解决方案3】:

      我有同样的问题,最后通过在 AndroidManifest.xml 文件中添加android:requestLegacyExternalStorage="true" 解决了它 关注话题here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-15
        • 2014-11-20
        相关资源
        最近更新 更多