How to upload a file using React Native?

I am building a React Native app for Android and iOS. I am trying to allow the user to download a PDF file at the click of a button.

  • react-native-file-download does not support Android
  • react-native-fs does nothing when I run downloadFile (nothing appears in the notification bar) and I cannot find the file after that. I added android.permission.WRITE_EXTERNAL_STORAGE to the Android manifest file. I double checked that the file I am trying to download exists (when it is not, the library throws an error)

I do not find other solutions to this problem. I found libraries for viewing PDF files, but I would like to allow the user to download the PDF file. could you help me?

+5
source share
2 answers

Just implemented the download function an hour ago: p

Follow these steps:

a) npm install react-native-fetch-blob

b) follow the installation instructions.

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

c) Finally, as I made it possible to upload files in my application:

 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 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 }) 
+6
source

If you use Expo, react-native-fetch-blob will not work. Use FileSystem .

Here is 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 file name instead of name.ext .

+3
source

Source: https://habr.com/ru/post/1268846/


All Articles