joltup / rn-fetch-blob

A project committed to making file access and data transfer easier, efficient for React Native developers.
MIT License
2.84k stars 787 forks source link

Show Downloaded File and Notification in Android Downloads App. #181

Open ghost opened 6 years ago

ghost commented 6 years ago

Hi,

I'm trying to make a pdf that I have downloaded via react-native-pdf visible in any of the file directories on android.

I can copy the filepath returned by react-native-pdf, add a notification using RNFetchBlob.android.addCompleteDownload and click on the file, which flicks back to my app, but only if app in foreground.

But I want user to be able to see file in the Files app on android.

savePdf = () => { const newPath = ${RNFetchBlob.fs.dirs.DocumentDir}/Invoice-${this.props.currentInvoiceNumber}.pdf

RNFetchBlob.fs.cp(this.state.filePath, newPath)
  .then(() => {
    if (Platform.OS === 'ios') {
      RNFetchBlob.ios.previewDocument(newPath)
    } else {
      RNFetchBlob.fs.scanFile([{ path: newPath, mime: 'application/pdf' }])
      .then(() => {
        RNFetchBlob.android.addCompleteDownload({
          title: `Invoice ${this.props.currentInvoiceNumber}`,
          description: 'desc',
          mime: 'application/pdf',
          path: newPath,
          showNotification: true,
          notification: true
        })
      })
      .catch((err) => {
      })
    }
  })
  .catch((err) => {
  })

}

simonedavico commented 6 years ago

I have the same issue currently, clicking the notification tries to open my app and I don't see the file through the Files application.

@joltup, any idea?

kuzkokov commented 5 years ago

Hey guys. Same thing with react-native-pdf and local downloads. I managed to solve this problem. Topic starter doesn't need it anymore for sure, but probably it might help future seekers. You also need permissions for Android, so here is the full code.

if (isIOS) {
  await RNFetchBlob.ios.previewDocument(path);
} else {
  const granted = await PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
    {
      title: 'Permission to save file into the file storage',
      message: 'The app needs access to your file storage so you can download the file',
      buttonNeutral: 'Ask Me Later',
      buttonNegative: 'Cancel',
      buttonPositive: 'OK',
    }
  );

  if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
    throw new Error();
  }

  const filePath = `${RNFetchBlob.fs.dirs.DownloadDir}/${fileName}`;
  RNFetchBlob.fs
    .cp(path, filePath)
    .then(() =>
      RNFetchBlob.android.addCompleteDownload({
        title: fileName,
        description: 'Download complete',
        mime: 'application/pdf',
        path: filePath,
        showNotification: true,
      })
    )
    .then(() =>
      RNFetchBlob.fs.scanFile([
        { path: filePath, mime: 'application/pdf' },
      ])
    );
}
nikbelikov commented 4 years ago

Hey guys. Same thing with react-native-pdf and local downloads. I managed to solve this problem. Topic starter doesn't need it anymore for sure, but probably it might help future seekers. You also need permissions for Android, so here is the full code.

if (isIOS) {
  await RNFetchBlob.ios.previewDocument(path);
} else {
  const granted = await PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
    {
      title: 'Permission to save file into the file storage',
      message: 'The app needs access to your file storage so you can download the file',
      buttonNeutral: 'Ask Me Later',
      buttonNegative: 'Cancel',
      buttonPositive: 'OK',
    }
  );

  if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
    throw new Error();
  }

  const filePath = `${RNFetchBlob.fs.dirs.DownloadDir}/${fileName}`;
  RNFetchBlob.fs
    .cp(path, filePath)
    .then(() =>
      RNFetchBlob.android.addCompleteDownload({
        title: fileName,
        description: 'Download complete',
        mime: 'application/pdf',
        path: filePath,
        showNotification: true,
      })
    )
    .then(() =>
      RNFetchBlob.fs.scanFile([
        { path: filePath, mime: 'application/pdf' },
      ])
    );
}

thank you very much! that helped me a lot!

Henriquehlr commented 1 year ago

Ei pessoal. A mesma coisa com react-native-pdf e downloads locais. Consegui resolver esse problema. O iniciador de tópico não precisa mais disso com certeza, mas provavelmente pode ajudar futuros buscadores. Você também precisa de permissões para Android, então aqui está o código completo.

if (isIOS) {
  await RNFetchBlob.ios.previewDocument(path);
} else {
  const granted = await PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
    {
      title: 'Permission to save file into the file storage',
      message: 'The app needs access to your file storage so you can download the file',
      buttonNeutral: 'Ask Me Later',
      buttonNegative: 'Cancel',
      buttonPositive: 'OK',
    }
  );

  if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
    throw new Error();
  }

  const filePath = `${RNFetchBlob.fs.dirs.DownloadDir}/${fileName}`;
  RNFetchBlob.fs
    .cp(path, filePath)
    .then(() =>
      RNFetchBlob.android.addCompleteDownload({
        title: fileName,
        description: 'Download complete',
        mime: 'application/pdf',
        path: filePath,
        showNotification: true,
      })
    )
    .then(() =>
      RNFetchBlob.fs.scanFile([
        { path: filePath, mime: 'application/pdf' },
      ])
    );
}

Fantastic thank you very much

Henriquehlr commented 1 year ago

the pdf file is being downloaded with 0bytes do you have any idea what it could be?

async downloadPDFContrato(item) { try { const permissionGranted = await this.requestStoragePermission();

  if (!permissionGranted) {
    console.warn(
      'Permissão não concedida para acessar o sistema de arquivos.',
    );
    return null;
  }

  let pdfData = await this.props.getContratoPDF(
    this.props.user,
    item.contrato,
  );
  const {nome, arquivo} = pdfData;

  const downloadsPath =
    Platform.OS === 'ios'
      ? RNFetchBlob.fs.dirs.DocumentDir
      : RNFetchBlob.fs.dirs.DownloadDir;

  const pdfBlob = arquivo;

  const filePath = `${downloadsPath}/${nome}`;

if (Platform.OS === 'ios') {
        await RNFetchBlob.ios.previewDocument(filePath);
      } else {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          {
            title: 'Permissão para salvar arquivo no armazenamento',
            message:
              'O aplicativo precisa de acesso ao seu armazenamento de arquivos para que você possa baixar o arquivo',
            buttonNeutral: 'Pergunte-me depois',
            buttonNegative: 'Cancelar',
            buttonPositive: 'OK',
          },
        );

        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          const fileName = nome;
          await RNFetchBlob.fs.cp(
            filePath,
            RNFetchBlob.fs.dirs.DownloadDir + `/${fileName}`,
          );

          await RNFetchBlob.android.addCompleteDownload({
            title: fileName,
            description: 'Download complete',
            mime: 'application/*',
            path: downloadsPath + `/${fileName}`,
            showNotification: true,
          });

          await RNFetchBlob.fs.scanFile([
            {
              path: downloadsPath + `/${fileName}`,
              mime: 'application/*',
            },
          ]);
        }
      }

} catch (error) {
  console.error('Erro ao fazer o download do PDF:', error);

  return null;
}

}