首页 > 解决方案 > 如何从 basse64 字符串下载 PDF

问题描述

我正在使用 api 来获取 base64 字符串,现在我想将其转换为普通的 pdf 并希望将其保存在下载中。我怎样才能做到这一点。

我尝试像下面给出的代码一样使用 rn-fetch-blob。

const { config, fs } = RNFetchBlob
                let DownloadDir = fs.dirs.DownloadDir;
                let options = {
                    addAndroidDownloads: {
                        useDownloadManager: true, // <-- this is the only thing required
                        // Optional, override notification setting (default to true)
                        notification: true,
                        // Optional, but recommended since android DownloadManager will fail when
                        // the url does not contains a file extension, by default the mime type will be text/plain
                        mime: 'application/pdf',
                        description: 'File downloaded by download manager.',
                        path: DownloadDir + '/' + 'test.pdf',
                    }
                }
        
                trackPromise(
                    config(options).fetch('get', Constant.url.BASE_URL + 'my url/which returns/base64 string', {
                        Authorization: 'Bearer' + token.access_token,
                    })
                        .then((res) => {
                            console.log('download resp', res)
                            console.log('The file saved to ', res.path());
                            let base64Str = res.data;
                            let pdfLocation = RNFetchBlob.fs.dirs.DocumentDir + '/' + 'test.pdf';
                            RNFetchBlob.fs.writeFile(pdfLocation, RNFetchBlob.base64.encode(base64Str), 'base64');

                            Common.showToast('File saved in Download folder', 'success');
                        })
                        .catch((err) => {
                            console.log(err);
                            showToast('Failed to download file', 'danger');
                            //throwException(err);
                        })
                );

请帮助我找到解决方案。提前致谢。

标签: javascriptreactjsreact-native

解决方案


推荐阅读