为了账号安全,请及时绑定邮箱和手机立即绑定

从目录共享文件

从目录共享文件

呼唤远方 2021-12-12 09:51:39
我有一个从外部设备读取值的应用程序。我将这些数据以 .csv 格式保存在下载目录中。我要做的是在单击它们时共享或打开此文件。我使用react-native FScomponentDidMount(){    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 文件的路径。你知道如何打开这个文件给用户选择方法的可能性吗?
查看完整描述

1 回答

?
红糖糍粑

TA贡献1815条经验 获得超6个赞

如果您已经正常下载文件到路径中,并且可以直接在手机上看到下载的文件,则可以使用文件选择器。

  1. npm i --save react-native-document-picker

  2. react-native link 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" />;

  }

}


查看完整回答
反对 回复 2021-12-12
  • 1 回答
  • 0 关注
  • 223 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号