uniapp—小程序、app、h5在线预览base64(pdf)

一、如果返回url


二、返回base64(pdf)
1、app
uniapp插件image-tools:图像转为base64、base64存储为图片(最新版本)
插件地址:https://ext.dcloud.net.cn/plugin?id=123

//结构


import {pathToBase64,base64ToPath} from 'image-tools'
//接口返回base64
 let result = res.data.result.replace(/[\r\n]/g, "");
 let pdfBase64 = `data:application/pdf;base64,${result}`;
    base64ToPath(pdfBase64)
        .then(path => {
            uni.openDocument({
                filePath: path,
                success: function(FileRes) {
                    console.log('打开成功');
                }
            });                                          
          .catch(error => {
                console.error(error)
         })

2、小程序

//结构


//接口返回base64
let result = res.data.result.replace(/[\r\n]/g, '');
let pdfBase64 = `data:application/pdf;base64,${result}`;
var fs = wx.getFileSystemManager();
let fileName = '';
var times = new Date().getTime();
fs.writeFile({   //保存本地临时路径
    filePath: wx.env.USER_DATA_PATH + '/' + times + '.pdf',
    data: wx.base64ToArrayBuffer(result.replace(/[\r\n]/g, '')),
    success: res => {
         let ll = wx.env.USER_DATA_PATH + '/' + times + '.pdf';
         wx.openDocument({
            fileType: 'pdf',
            showMenu: false,
            filePath: wx.env.USER_DATA_PATH + '/' + times + '.pdf',
            success: function(res) {
            console.log('打开PDF成功');
        },
        fail(err) {
            console.log(err);
         }
        });
    }
});

3、h5
下载pdf.js : https://mozilla.github.io/pdf.js/getting_started/#download

  • 注意:路径要放在static文件夹下
//结构


//data里边定义
viewerUrl: '/static/hybrid/html/web/viewer.html',
allUrl:''

//接口请求返回base64
let result = res.data.result.replace(/[\r\n]/g, "");
let pdfBase64 = `data:application/pdf;base64,${result}`;
let pdf = URL.createObjectURL(this.base64ToBlob(pdfBase64));
// #ifdef H5
//下面的路径就是pdf.js文件夹下对应的路径,用来格式化展示pdf
this.allUrl = this.viewerUrl + `?file=${pdf}`
// #endif

// base64转blob
     base64ToBlob(base64Data) {
        let arr = base64Data.split(','),
            fileType = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            l = bstr.length,
            u8Arr = new Uint8Array(l);
            while (l--) {
                u8Arr[l] = bstr.charCodeAt(l);
            }
            return new Blob([u8Arr], {
                type: fileType
            });
    }

你可能感兴趣的:(uniapp—小程序、app、h5在线预览base64(pdf))