我有一个可以从外部设备读取值的应用程序。我将这些数据以 .csv 格式保存在下载目录中。
我要做的是在单击它们时共享或打开此文件。
我使用react-native FS
componentDidMount(){
this.readingValue()
}
async readingValue() {
// get a list of files and directories in the main bundle :ExternalStorageDirectoryPath
const elementiDirectory = await RNFS.readDir(RNFS.ExternalStorageDirectoryPath + '/Download/')
const pathElementi = elementiDirectory.map(e => e.path);
//console.log("filter " + pathElementi)
const pathCSV = pathElementi.filter(path => {
const reg = /sd\d+\.csv/;
return reg.test(path);
});
console.log("risultati " + pathCSV)
this.setState({risultati : pathCSV});
}
render() {
return (
<View>
<Text>{this.state.risultati}</Text>
</View>
);
}
此代码显示保存的 .csv 文件的路径。你知道我该怎么做才能打开这个文件,让用户可以选择方法吗?
最佳答案
如果您已正常将文件下载到该路径,并且可以直接在手机上看到下载的文件,则可以使用文件选择器。
npm i --save react-native-document-picker
react-native链接react-native-document-picker
示例
import DocumentPicker from 'react-native-document-picker';
// Pick a single file
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.images],
});
console.log(
res.uri,
res.type, // mime type
res.name,
res.size
);
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
// Pick multiple files
try {
const results = await DocumentPicker.pickMultiple({
type: [DocumentPicker.types.images],
});
for (const res of results) {
console.log(
res.uri,
res.type, // mime type
res.name,
res.size
);
}
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
如果您需要共享,请创建一个 URL 来下载该文件。
示例
import {Share } from 'react-native';
class ShareExample extends Component {
onShare = async () => {
try {
const result = await Share.share({
message: 'csv file download',
url: "file:///storage/emulated/0/yourFileName/downfile.csv",
});
if (result.action === Share.sharedAction) {
if (result.activityType) {
// shared with activity type of result.activityType
} else {
// shared
}
} else if (result.action === Share.dismissedAction) {
// dismissed
}
} catch (error) {
alert(error.message);
}
};
render() {
return <Button onPress={this.onShare} title="Share" />;
}
}
关于javascript - 共享目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647419/