How to download a file with React Native?

前端 未结 3 1312
花落未央
花落未央 2020-12-02 17:32

I am building an app with React Native, for Android and iOS. I am trying to let the user download a PDF file when clicking on a button.

  • react-native-file-downl
相关标签:
3条回答
  • 2020-12-02 17:44

    If you're using Expo, react-native-fetch-blob won't work. Use FileSystem.

    Here's a working example:

    const { uri: localUri } = await FileSystem.downloadAsync(remoteUri, FileSystem.documentDirectory + 'name.ext');
    

    Now you have localUri with the path to the downloaded file. Feel free to set your own filename instead of name.ext.

    0 讨论(0)
  • 2020-12-02 17:49

    Just implemented the download feature an hour ago :p

    Follow these steps:

    a) npm install rn-fetch-blob

    b) follow the installation instructions.

    b2) if you want to manually install the package without using rnpm, go to their wiki.

    c) Finally, that's how I made it possible to download files within my app:

    const { config, fs } = RNFetchBlob
    let PictureDir = fs.dirs.PictureDir // this is the pictures directory. You can check the available directories in the wiki.
    let options = {
      fileCache: true,
      addAndroidDownloads : {
        useDownloadManager : true, // setting it to true will use the device's native download manager and will be shown in the notification bar.
        notification : false,
        path:  PictureDir + "/me_"+Math.floor(date.getTime() + date.getSeconds() / 2), // this is the path where your downloaded file will live in
        description : 'Downloading image.'
      }
    }
    config(options).fetch('GET', "http://www.example.com/example.pdf").then((res) => {
      // do some magic here
    })
    
    0 讨论(0)
  • 2020-12-02 17:53

    I had the same issue, got it working using Expo WebBrowser Module

    // install module 
    npm install react-native-webview
    
    // import the module
    import * as WebBrowser from 'expo-web-browser';
    
    // then in your function you can call this function
    await WebBrowser.openBrowserAsync(file_ur);
    

    it will open preview of the file and then user can download using share button.

    0 讨论(0)
提交回复
热议问题