标签: react-native-fs

尝试向React Native添加openFile方法,无法调用getCurrentActivity

在react-native-fs的分支内(https://github.com/johanneslumpe/react-native-fs),我正在尝试添加以下代码:

public class RNFSManager extends ReactContextBaseJavaModule {

    public RNFSManager(ReactApplicationContext reactContext) {
      super(reactContext);
    }
    @ReactMethod
    public void openFile(String filepath, Callback callback) {
        try {
          File file = new File(filepath);
          MimeTypeMap myMime = MimeTypeMap.getSingleton();
          Intent newIntent = new Intent(Intent.ACTION_VIEW);
          String mimeType = myMime.getMimeTypeFromExtension(fileExt(filepath).substring(1));
          newIntent.setDataAndType(Uri.fromFile(file), mimeType);
          newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          Activity currentActivity = getCurrentActivity();
          if (currentActivity != null) {
            currentActivity.startActivity(newIntent);
          } else {
            this.getReactApplicationContext().startActivity(newIntent);
          }
        } catch (Exception ex) {
          ex.printStackTrace();
          callback.invoke(makeErrorPayload(ex));
        }
      }
Run Code Online (Sandbox Code Playgroud)

但是当我构建它时,我收到此错误:

.../android/src/main/java/com/rnfs/RNFSManager.java:138: error: cannot find symbol
      Activity currentActivity = getCurrentActivity(); …
Run Code Online (Sandbox Code Playgroud)

java android react-native react-native-fs

5
推荐指数
1
解决办法
393
查看次数

RNFS.exists()始终返回TRUE

我正在使用react-native-fs,出于某种原因,每当我使用exists()方法时,它总是返回为TRUE.我的代码示例如下所示:

let path_name = RNFS.DocumentDirectoryPath + "/userdata/settings.json";

if (RNFS.exists(path_name)){
    console.log("FILE EXISTS")
    file = await RNFS.readFile(path_name)
    console.log(file)
    console.log("DONE")
}
else {
    console.log("FILE DOES NOT EXIST")
}
Run Code Online (Sandbox Code Playgroud)

控制台的输出是"FILE EXISTS",然后抛出一个错误,说:

错误:ENOENT:没有这样的文件或目录,打开/data/data/com.test7/files/userdata/settings.json'

如何使用该exists方法存在,而不是readFile方法?

在进一步检查时,无论文件名是什么,RNFS.exists()似乎总是返回true.为什么它总是回归真实?

path_name的显示说/data/data/com.test7/files/userdata/settings.json.

即使我将代码更改为无意义的代码,如下面的代码:

if (RNFS.exists("blah")){
    console.log("BLAH EXISTS");
} else {
    console.log("BLAH DOES NOT EXIST");
}
Run Code Online (Sandbox Code Playgroud)

它仍然评估为true并显示消息:

BLAH EXISTS
Run Code Online (Sandbox Code Playgroud)

我已经显示了目录的内容并验证了这些文件不存在.

react-native react-native-fs

5
推荐指数
1
解决办法
3230
查看次数

React-Native 方法挂起并且不会抛出错误

我正在使用 react-native-fs 模块,但是我的应用程序似乎冻结在它上面。我的 React-Native 方法之一中有以下代码段:

console.log("One")
await RNFS.downloadFile({
    fromUrl: 'http://example.com/data/blah.zip',
    toFile: RNFS.DocumentDirectoryPath + "/userdata/blah.zip",
}).promise
console.log("Two")
Run Code Online (Sandbox Code Playgroud)

“一”会回显到控制台,但“二”永远不会得到回显。没有抛出错误。URL 确实存在并且 RNFS.DocumentDirectoryPath + /userdata 目录确实存在。

我究竟做错了什么?为什么不抛出错误?为什么它挂在这一点上?

更新

不幸的是,因为它似乎只是有时发生,所以很难诊断或进行较小的测试。我必须做的是,当发生这种情况时,我必须关闭 react-native 命令提示符节点窗口并重新运行react-native run-android. 一旦我这样做了,它就会完美地进行。

react-native react-native-fs

5
推荐指数
1
解决办法
718
查看次数

反应原生 fs 库不写入文件

当我使用 react-native-fs 创建文件时,回调成功到达,但该文件不在我的 android/data/com.myapp/files/test.txt 库中。

logcat 中没有错误,所以我想知道为什么我的带有简单 App.js 的代码不起作用。

    /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ToastAndroid
} from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});
var RNFS = require('react-native-fs');
 // create a …
Run Code Online (Sandbox Code Playgroud)

react-native react-native-fs

5
推荐指数
1
解决办法
5611
查看次数

从 react-native 获取文件以上传与 `<input type="file" onChange={this.fileChangedHandler}> 相同的图像

我试过做

var photo = {
    uri: uriFromCameraRoll,
    type: 'image/jpeg',
    name: 'photo.jpg',
};
Run Code Online (Sandbox Code Playgroud)

并使用

公理

var body = new FormData();
body.append('authToken', 'secret');
body.append('photo', photo);
body.append('title', 'A beautiful photo!');

const config = {
            headers: {
                'content-Type': 'multipart/form-data'
            }
        }
 MY_API().then(instance => {

// it is axios instance
            instance.post("/api/v1/upload",
                { body }
                , config).then(res => {
                    console.log(JSON.stringify(res));

                }).catch(err => {
                    console.log(err);
                })
        }
        )
Run Code Online (Sandbox Code Playgroud)

在删除配置我得到

错误 503

并通过配置它给出

错误:多部分:未找到边界

并且与 POSTMAN 一起工作也很好......连同标题

我也尝试上传 File (blob) ,但同样的错误

错误:多部分:未找到边界

 dataURLtoFile(dataurl, filename) {
    var arr = …
Run Code Online (Sandbox Code Playgroud)

javascript node.js reactjs react-native react-native-fs

5
推荐指数
1
解决办法
3933
查看次数

EISDIR:对目录的非法操作,在 React Native 文件系统中读取

我正在尝试使用以下代码将文件复制到另一个外部文件夹的简单代码:

RNFS.copyFile(sourcePath, destinationPath)
.then(result => {
  console.log('file copied:', result);
})
.catch(err => {
  console.log('error: ', err.message, err.code);
});
Run Code Online (Sandbox Code Playgroud)

我已经授予Android.Permission在外部目录中进行读写的权限,但它仍然返回此错误:

error:  EISDIR: illegal operation on a directory, read '/storage/emulated/0/' EISDIR
Run Code Online (Sandbox Code Playgroud)

这是依赖项:

"react": "16.9.0",
"react-native": "0.61.2",
"react-native-fs": "^2.15.2"
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我请求正确的许可吗?

PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE 
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
Run Code Online (Sandbox Code Playgroud)

提前感谢您的帮助

android react-native react-native-android react-native-fs

5
推荐指数
1
解决办法
7994
查看次数

使用React Native FS将文件写入Android外部存储

我的 React Native Android 应用程序需要将 JSON 文件保存在外部存储的特殊文件夹中。我尝试使用 RNFS ( https://github.com/itinance/react-native-fs ) 这样做:

const saveData = async () => {
    var path = `${RNFS.ExternalStorageDirectoryPath}/MyApp`;
    RNFS.mkdir(path);
    path += '/data.json';
    RNFS.writeFile(path, JSON.stringify(getData()), 'utf8')
      .then((success) => {
        console.log('Success');
      })
      .catch((err) => {
        console.log(err.message);
      });
  }
Run Code Online (Sandbox Code Playgroud)

它运行良好,但在 Android Q 设备上失败。显示此错误:

Error: Directory could not be created

如果我尝试编写一个普通文件而不创建目录,则会抛出此错误:

ENOENT: open failed: ENOENT (No such file or directory), open '/storage/emulated/0/data.json'

但是,我已将此权限添加到我的AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Run Code Online (Sandbox Code Playgroud)

并在设置中授予外部存储权限。但如果我将其更改RNFS.ExternalStorageDirectoryPathRNFS.DocumentDirectoryPath它,它就不会出现任何错误。但我需要访问外部存储。有什么办法可以做到吗?

android react-native react-native-fs android-10.0

5
推荐指数
2
解决办法
2万
查看次数

react-native-fs [错误:无法创建目录]

我正在尝试使用创建目录RNFS.mkdir,但警告“无法创建目录”...

"react-native-fs": "^2.18.0",
"react-native": "0.64.0",
Run Code Online (Sandbox Code Playgroud)

我用来编写的函数如下:

const phoneStorageDir = RNFS.ExternalStorageDirectoryPath + '/MyApp/pictures/';

const createAppFolder = async () => {
  if (Platform.OS === 'android') {
    try {
      const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        {
          title: 'Permissions for write access',
          message: 'Give permission to your storage to write a file',
          buttonPositive: 'ok',
        },
      );
      if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        await RNFS.mkdir(phoneStorageDir);
      } else {
        console.log('permission denied');
        return;
      }
    } catch (err) {
      console.warn(err);
      return;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我还添加到它的清单文件:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" …
Run Code Online (Sandbox Code Playgroud)

react-native react-native-fs

5
推荐指数
1
解决办法
152
查看次数

将文件保存在 Documents/Downloads 中

是否可以在文档或下载中使用react-native保存文件?我正在尝试使用react-native-fs保存pdf文件:

let file = await RNHTMLtoPDF.convert(options)
const destinationPath = RNFS.DocumentDirectoryPath + "/" + fileName + ".pdf"
RNFS.copyFile(file.filePath, destinationPath)
Run Code Online (Sandbox Code Playgroud)

但它保存在根目录(/​​data/user /0/com.prodhealth.mobile.Dev/files/TestTest_2022-02-22_2022-02-22.pdf )中,普通用户无法访问。

有没有办法直接将其保存在手机内部存储的文档/下载中?我需要该用户可以轻松访问该文件。

pdf storage react-native react-native-fs

5
推荐指数
1
解决办法
9448
查看次数

如何使用react-query和react-native-fs保存excel文件?

我正在使用包含 axios 的 React-query 来获取 API,并尝试将响应保存/下载到 Excel 文件并存储它。下面是代码和 api 响应。我无法确定是否遗漏了任何标头、响应类型是否不正确或 RNFS.writeFile 调用是否错误。

\n
import axios from 'axios';\nimport RNFS from 'react-native-fs';\nimport {useQuery} from 'react-query';\n\nexport function useExportGains(\n  accountId: number,\n  fileFormat: string,\n  fromDate: string,\n  toDate: string,\n) {\n  const getReport = async () => {\n    const baseApiUrl = 'https://devenv.product.com/API'; // api url\n    const Api = axios.create({baseURL: baseApiUrl});\n    const params = {\n      fromDate: fromDate,\n      toDate: toDate,\n      contextFilter: {\n        appUserIds: [1],\n      },\n    };\n\n    const mimeType =\n      fileFormat === 'pdf'\n        ? 'application/pdf'\n        : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';\n\n    Api.get(`Reporting/AccountAnalytics/${accountId}/exportGains/${fileFormat}`, {\n      params,\n …
Run Code Online (Sandbox Code Playgroud)

javascript react-native react-native-fs react-query

5
推荐指数
0
解决办法
1423
查看次数