简体   繁体   中英

Create and download text file in react native

I want to convert a string to a text file on the same side of the client(App) and download it to my phone. How can I do this?

You can use react-native-fs for this task. It provides native filesystem access for react-native.

var RNFS = require('react-native-fs');

var path = RNFS.DocumentDirectoryPath + '/test.txt';

// write the file
RNFS.writeFile(path, 'your text comes here', 'utf8')
  .then((success) => {
    console.log('FILE WRITTEN!');
  })
  .catch((err) => {
    console.log(err.message);
  });

This might help you:

var fs = require('react-native-fs');

  const readFile = async () => {
    // console.log('fs.DocumentDirectoryPath', fs.DocumentDirectoryPath);
    fs.mkdir(fs.DocumentDirectoryPath)
      .then(() => downloadWithRNFS())
      .catch(err => console.log(err));
  };

  const downloadWithRNFS = async () => {
    const options = {
      fromUrl: 'https://facebook.github.io/react-native/img/header_logo.png',
      toFile: `${fs.DocumentDirectoryPath}/test.txt`,
    };
    fs.downloadFile(options)
      .promise.then(res => {
        console.log('downloadWithRNFS', res);
      })
      .catch(err => console.log(err));
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM