sguha
sguha

Reputation: 2197

Save Blob to FileSystem in React Native Expo

I am trying to download a PDF and share it via the 'expo-sharing' SDK. I can't use FileSystem.createDownloadResumable because the document is available via a POST request.

Upvotes: 2

Views: 7064

Answers (1)

sguha
sguha

Reputation: 2197

Download it as a blob and use FileReader to convert it to a base64 string to pass to FileSystem.writeAsStringAsync

const response = await axios.post(URL_PDF_CONTENT, { Benefits: payload }, { responseType: 'blob' });

const fr = new FileReader();
fr.onload = async () => {
  const fileUri = `${FileSystem.documentDirectory}/pdf.pdf`;
  await FileSystem.writeAsStringAsync(fileUri, fr.result.split(',')[1], { encoding: FileSystem.EncodingType.Base64 });
  Sharing.shareAsync(fileUri);
};
fr.readAsDataURL(response.data);

Upvotes: 17

Related Questions