我正在使用React Native为Android和iOS构建应用程序.我试图让用户在单击按钮时下载PDF文件.
android.permission.WRITE_EXTERNAL_STORAGE
到Android Manifest文件中.我仔细检查了我试图下载的文件是否存在(当它没有时,库会抛出错误)我没有找到解决此问题的其他解决方案.我找到了用于查看PDF的库,但我想让用户下载PDF.请问你能帮帮我吗?
我正在使用react-native-fs下载文件(pdf、word、excel、png 等),我需要在其他应用程序中打开它。是否可以使用链接打开下载的文件,或者更好地打开一个包含可能的应用程序的对话框,例如使用共享时?Linking
在下面的代码中尝试打开文件但它立即关闭而没有任何通知,但我的应用程序仍然正常工作。是否有一些特殊的方法可以为特定文件类型构建用于深层链接的 URL?关于最佳解决方案的任何想法?
我看到有旧包react-native-file-opener但它不再维护。这个解决方案会很棒。
下载组件的简化代码:
import React, { Component } from 'react';
import { Text, View, Linking, TouchableOpacity } from 'react-native';
import { Icon } from 'react-native-elements';
import RNFS from 'react-native-fs';
import { showToast } from '../../services/toasts';
class DownloadFile extends Component {
state = {
isDone: false,
};
handleDeepLinkPress = (url) => {
Linking.openURL(url).catch(() => {
showToast('defaultError');
});
};
handleDownloadFile = () => {
RNFS.downloadFile({
fromUrl: 'https://www.toyota.com/content/ebrochure/2018/avalon_ebrochure.pdf',
toFile: `${RNFS.DocumentDirectoryPath}/car.pdf`,
}).promise.then(() …
Run Code Online (Sandbox Code Playgroud) android ios react-native react-native-fs react-native-fetch-blob
我正在使用react-native-fs,我正在尝试将pdf文件的base64保存到我的android模拟器文件系统中.
我从服务器收到base64编码的pdf.
然后我用行解码base64字符串:
var pdfBase64 = 'data:application/pdf;base64,'+base64Str;
Run Code Online (Sandbox Code Playgroud)
saveFile()函数
saveFile(filename, pdfBase64){
// create a path you want to write to
var path = RNFS.DocumentDirectoryPath + '/' + filename;
// write the file
RNFS.writeFile(path, base64Image, 'base64').then((success) => {
console.log('FILE WRITTEN!');
})
.catch((err) => {
console.log("SaveFile()", err.message);
});
}
Run Code Online (Sandbox Code Playgroud)
错误
当我尝试保存pdfBase64时,saveFile()函数捕获以下错误:
bad base-64
Run Code Online (Sandbox Code Playgroud)
问题
任何人都可以告诉我哪里或者我做错了什么?谢谢.
我使用最新版本创建了一个新的react-native应用程序,默认测试运行良好。\n然后我使用\'react-native-fs\'lib在我的应用程序中写入一个文件,它运行良好。\n但我尝试运行测试命令,失败。
\n\n> TestJest@0.0.1 test D:\\test\\TestJest\n> jest\n\n FAIL __tests__\\index.android.js\n \xe2\x97\x8f Test suite failed to run\n\nTypeError: Cannot read property \'RNFSFileTypeRegular\' of undefined\n\n at Object.<anonymous> (node_modules\\react-native-fs\\FS.common.js:17:36)\n at Object.<anonymous> (index.android.js:14:20)\n\nTest Suites: 1 failed, 1 total\nTests: 0 total\nSnapshots: 0 total\nTime: 0.8s\nRan all test suites.\nnpm ERR! Test failed. See above for more details.\n
Run Code Online (Sandbox Code Playgroud)\n\n我已按照Jest 的手册文档进行操作,但尚未解决错误。这是我的示例存储库。您能看一下我的示例存储库并让我知道我错了什么吗?
\n\n谢谢。
\n我正在尝试使用react-native-fs和react-native-document picker将从文档选择器中选择的文件移动到文档目录。
但是,我收到以下错误:
Error: “file name.mp3” couldn’t be moved to “Documents” because either the former doesn't exist, or the folder containing the latter doesn't exist.
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
仅供参考,我正在使用iOS。
openDocumentPicker() {
DocumentPicker.show({
filetype: ['public.audio'],
},(error,url) => {
console.log(url);
this.saveAudio(url);
});
}
saveAudio(url) {
var destPath = RNFS.DocumentDirectoryPath + '/' + 'name';
RNFS.moveFile(url, destPath)
.then((success) => {
console.log('file moved!');
})
.catch((err) => {
console.log("Error: " + err.message);
});
}
Run Code Online (Sandbox Code Playgroud) 我正在使用react-native-fs从服务器下载文件并保存它们。下载后,我将使用react-native-file-viewer打开它们。这个过程完全正常:我可以在查看器中下载并打开它,但我无法从查看器中将文件保存在文件应用程序中,尽管我可以保存在 iCloud 中但不能保存在 iPhone 中。下载的文件存储在类似的地方
/var/mobile/Containers/Data/Application/CCF6CD16-A62A-48BB-92F3-3021195CFE0C/Documents/react-native-pdf.pdf
Run Code Online (Sandbox Code Playgroud)
但这没有显示在“文件”应用程序中。
我用来下载和查看文件的代码如下
RNFS.downloadFile({
fromUrl: 'http://www.mywebsite.com/react-native-pdfurl.pdf',
toFile: `${RNFS.DocumentDirectoryPath}/react-native-pdfurl.pdf`,
}).promise.then((r) => {
console.log('yo yo yo ');
this.setState({ isDone: true });
const path = `${RNFS.DocumentDirectoryPath}/react-native-pdfurl.pdf`;
FileViewer.open(path)
.then(() => {
// success
})
.catch(error => {
// error
});
RNFS.readDir(RNFS.DocumentDirectoryPath).then(files => {
console.log(files);
})
.catch(err => {
console.log(err.message, err.code);
});
});
Run Code Online (Sandbox Code Playgroud)
readDir 获取保存的文件的名称路径。但这并没有反映在“文件”应用程序中的任何文件夹中。我的问题是如何以文件应用程序中显示的方式保存文件。
我正在将图像文件从React Native上传到AWS Lambda(Node 10.x),并想验证我发送的文件的哈希与收到的文件匹配。为此,我在React Native和Lambda中再次使用了哈希,但是哈希值始终不匹配。这是我尝试过的相关代码。
反应本机
import RNFS from "react-native-fs";
const contentChecksum = await RNFS.hash(post.contentUrl, "md5");
Run Code Online (Sandbox Code Playgroud)
Lambda(节点)
import AWS from "aws-sdk";
const crypto = require("crypto");
const s3 = new AWS.S3();
const data = await s3
.getObject({
Bucket: file.bucket,
Key: file.key
})
.promise();
const contentChecksum = crypto
.createHash("md5")
.update(data.Body)
.digest("hex");
Run Code Online (Sandbox Code Playgroud)
这些校验和永远不匹配。我试过base64
在Node(data.Body.toString("base64")
)中也使用编码sha256
。计算校验和以便它们在React Native和Node中匹配的诀窍是什么?
编辑:这是最近一次测试的结果。
post.contentUrl
: file:///Users/xxxxxxx/Library/Developer/CoreSimulator/Devices/2F2F4FD3-574E-40D7-BE6B-7080E926E70A/data/Containers/Data/Application/65A3FF67-98B2-444D-B75D-3717C1274FBC/Library/Caches/Camera/FDCD8F90-D24F-4E64-851A-96AB388C4B59.jpg
(该文件在iPhone上是本地的)
contentChecksum
来自React Native:48aa5cdb30f01719a2b12d481dc22f04
contentChecksum
来自Node(Lambda):7b30b61a55d2c39707082293c625fc10
data.Body
是一个Buffer
。
我还注意到,S3对象上的eTag属性与我在Node中计算的md5校验和匹配。由于eTag 通常是文件的md5哈希值,因此这告诉我在React Native中可能会错误地计算哈希值,但是我不确定如何。我正在使用react-native-fs包中的哈希函数。
我正在尝试在 React Native 中实现一些功能:我有一个在 React Native 视频组件中显示的视频网址,我如何提供一个按钮来在移动设备中下载相同的视频,但它不应该出现在图库中。另外,如果视频是私有的,则可以在哪里传递标题以及如何传递?
在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) 我的 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.ExternalStorageDirectoryPath
为RNFS.DocumentDirectoryPath
它,它就不会出现任何错误。但我需要访问外部存储。有什么办法可以做到吗?
react-native ×10
react-native-fs ×10
android ×3
ios ×2
android-10.0 ×1
aws-lambda ×1
base64 ×1
iphone ×1
java ×1
javascript ×1
jestjs ×1
node.js ×1