ammarahm-ed / react-native-scoped-storage

MIT License
58 stars 10 forks source link

Download file from API #32

Closed gkasireddy202 closed 2 years ago

gkasireddy202 commented 2 years ago

Hi,

How to download files to internal storage from API. I have an API for downloading files from SharePoint rest API. Any method?

Thank you.

vlxdisluv commented 2 years ago

U can download through any convenient way but before you have to get access to directory by call the openDocumentTree method and after successful download call writeFile something like that:

const scopedStorageData = await ScopedStorage.openDocumentTree(true);

const availableStoragePath =  '${ExternalDirectoryPath}/${YOUR_DIRECTORY_NAME_IF_NEED}';

const fileName = 'some.png';
const mime = 'image/png';

const androidOptions: RNFetchBlobConfig = {
  fileCache: true,
  addAndroidDownloads: {
    path: '${availableStoragePath}/${fileName}',
  },
};

const downloadedFile = await RNFetchBlob.config(androidOptions).fetch('GET', remoteImageUrl);

await ScopedStorage.writeFile(scopedStorageData.uri, fileName, mime, downloadedFile.base64(), 'base64');

ExternalDirectoryPath takes from react-native-fs

ammarahm-ed commented 2 years ago

The above example is good enough. Thanks @vlxdisluv

gkasireddy202 commented 2 years ago

@vlxdisluv - Thanks for the reply.

I am getting error at const androidOptions:

const fetchConfig = {
  fileCache: true,
  addAndroidDownloads: {
    path: `${availableStoragePath}/${fileName}`,
  },
};

RNFetchBlobConfig : Type annotations can only be used in Typescript files.

How to send token along with the URL ?

vlxdisluv commented 2 years ago

@gkasireddy202

it is perfectly described in doc for rn-fetch-blob

ammarahm-ed commented 2 years ago

@vlxdisluv - Thanks for the reply.

I am getting error at const androidOptions:

const fetchConfig = {
  fileCache: true,
  addAndroidDownloads: {
    path: `${availableStoragePath}/${fileName}`,
  },
};

RNFetchBlobConfig : Type annotations can only be used in Typescript files.

How to send token along with the URL ?

You are trying to assign fetch config to a typescript type & using it in a JS file which doesn't work.

I have made some edits.

gkasireddy202 commented 2 years ago

@vlxdisluv - Thanks for replying.

Now it is working fine. Can I use mime like below. From API response we don't get mime.

const mime = '/'; await ScopedStorage.writeFile(scopedStorageData.uri, fileName, mime, downloadedFile.base64(), 'base64');

ammarahm-ed commented 2 years ago

@gkasireddy202 You can I think. Something like /. Although if you are requesting something from API, usually you should know what the file type is. You can also check the response headers to look for data type.

gkasireddy202 commented 2 years ago

@ammarahm-ed - Thanks for the reply. I will check the response header for the data type.