React native: how to get file size, mime type and extension?

I know react-native-fs and react-native-fetch-blob , but I miss the simple helper functions like getFileInfo(file) .

Desired pseudo code:

 let fileInfo = getFileInfo('path/to/my/file.txt'); console.log('file size: ' + fileInfo.size); console.log('mime type: ' + fileInfo.type); console.log('extension: ' + fileInfo.extension); 

What is the correct way to get file size, mime type and extension?

Thanks in advance!

+6
source share
3 answers

To get the file size using response-native-fetch-blob, I used the following code

For this you need to install base-64

 var base64 = require('base-64'); RNFetchBlob.fs.readFile(filePath, 'base64') .then((data) => { var decodedData = base64.decode(data); var bytes=decodedData.length; if(bytes < 1024) console.log(bytes + " Bytes"); else if(bytes < 1048576) console.log("KB:"+(bytes / 1024).toFixed(3) + " KB"); else if(bytes < 1073741824) console.log("MB:"+(bytes / 1048576).toFixed(2) + " MB"); else console.log((bytes / 1073741824).toFixed(3) + " GB"); }) 

Explanation:

  • The above code decodes base64 data into a string such as atob ().
  • Next string search length
  • From this value I have to calculate the file size.

If the file is too large, use RNFetchBlob.fs.readStream instead of RNFetchBlob.fs.readFile

I get byte calculations from SO size conversion

The code may be too long to calculate the file size. If anyone finds the easiest way, advise me

+2
source

You can get blob data using the reaction-native-fetch-blob and use action-native-mime types to get the extension

 const res = yield RNFetchBlob.config({fileCache: false}).fetch('GET', url, {}) const blob = yield res.blob().then((blob) => { mimetype.extension(blob.type) } ) 
+1
source

With response-native-fetch-blob, you can get the file size using the code below:

 RNFetchBlob.fs.stat(PATH_OF_THE_TARGET) .then((stats) => {}) .catch((err) => {}) 

The response statistics contains the following information:

 { // file name filename : 'foo.png', // folder of the file or the folder itself path : '/path/to/the/file/without/file/name/', // size, in bytes size : 4901, // `file` or `directory` type : 'file', // last modified timestamp lastModified : 141323298 } 

Source: https://github.com/wkh237/react-native-fetch-blob/wiki/File-System-Access-API#user-content-statpathstringpromisernfetchblobstat

+1
source

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


All Articles