• uniapp通过url或base64打开pdf文件


    1、通过url打开pdf文件:

      //通过url打开pdf文件
      openPdfFileByUrl(pdfUrl: string) {
        uni.showLoading({
          title: "下载中,请稍后...",
          mask: true,
        });
        uni.downloadFile({
          url: pdfUrl,
          success: function (res: any) {
            uni.hideLoading();
            console.log("下载成功!");
            //新开页面打开pdf文档:https://uniapp.dcloud.net.cn/api/file/file.html#opendocument
            uni.openDocument({
              filePath: res.tempFilePath,
              fileType: "pdf",
              success: function (res) {
                console.log("打开文档成功");
              },
            });
          },
          fail: function (res: any) {
            uni.hideLoading();
            uni.showToast({
              title: "下载失败",
              icon: "none",
            });
          },
        });
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    2、接口返回的是base64,打开pdf:

    
      import { base64ToPath } from ".../js/image-tools.js";
    
      ......
    
     //通过base64打开pdf文件
     openPdfFileByUrl(base64Data: string) {
        let result = base64Data.replace(/[\r\n]/g, "");
        let pdfBase64 = `data:application/pdf;base64,${result}`;
        base64ToPath(pdfBase64)
          .then((path) => {
            uni.openDocument({
              filePath: path,
              success: function (FileRes) {
                console.log("打开成功");
              },
              fail: (res) => {
                console.log("打开失败");
              },
            });
          })
          .catch((error) => {
            console.error(error);
          });
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    其中,image-tools.js代码:

    function getLocalFilePath(path) {
        if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
            return path
        }
        if (path.indexOf('file://') === 0) {
            return path
        }
        if (path.indexOf('/storage/emulated/0/') === 0) {
            return path
        }
        if (path.indexOf('/') === 0) {
            var localFilePath = plus.io.convertAbsoluteFileSystem(path)
            if (localFilePath !== path) {
                return localFilePath
            } else {
                path = path.substr(1)
            }
        }
        return '_www/' + path
    }
    
    function dataUrlToBase64(str) {
        var array = str.split(',')
        return array[array.length - 1]
    }
    
    var index = 0
    function getNewFileId() {
        return Date.now() + String(index++)
    }
    
    function biggerThan(v1, v2) {
        var v1Array = v1.split('.')
        var v2Array = v2.split('.')
        var update = false
        for (var index = 0; index < v2Array.length; index++) {
            var diff = v1Array[index] - v2Array[index]
            if (diff !== 0) {
                update = diff > 0
                break
            }
        }
        return update
    }
    
    export function pathToBase64(path) {
        return new Promise(function(resolve, reject) {
            if (typeof window === 'object' && 'document' in window) {
                if (typeof FileReader === 'function') {
                    var xhr = new XMLHttpRequest()
                    xhr.open('GET', path, true)
                    xhr.responseType = 'blob'
                    xhr.onload = function() {
                        if (this.status === 200) {
                            let fileReader = new FileReader()
                            fileReader.onload = function(e) {
                                resolve(e.target.result)
                            }
                            fileReader.onerror = reject
                            fileReader.readAsDataURL(this.response)
                        }
                    }
                    xhr.onerror = reject
                    xhr.send()
                    return
                }
                var canvas = document.createElement('canvas')
                var c2x = canvas.getContext('2d')
                var img = new Image
                img.onload = function() {
                    canvas.width = img.width
                    canvas.height = img.height
                    c2x.drawImage(img, 0, 0)
                    resolve(canvas.toDataURL())
                    canvas.height = canvas.width = 0
                }
                img.onerror = reject
                img.src = path
                return
            }
            if (typeof plus === 'object') {
                plus.io.resolveLocalFileSystemURL(getLocalFilePath(path), function(entry) {
                    entry.file(function(file) {
                        var fileReader = new plus.io.FileReader()
                        fileReader.onload = function(data) {
                            resolve(data.target.result)
                        }
                        fileReader.onerror = function(error) {
                            reject(error)
                        }
                        fileReader.readAsDataURL(file)
                    }, function(error) {
                        reject(error)
                    })
                }, function(error) {
                    reject(error)
                })
                return
            }
            if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
                wx.getFileSystemManager().readFile({
                    filePath: path,
                    encoding: 'base64',
                    success: function(res) {
                        resolve('data:image/png;base64,' + res.data)
                    },
                    fail: function(error) {
                        reject(error)
                    }
                })
                return
            }
            reject(new Error('not support'))
        })
    }
    
    export function base64ToPath(base64) {
        return new Promise(function(resolve, reject) {
            if (typeof window === 'object' && 'document' in window) {
                base64 = base64.split(',')
                var type = base64[0].match(/:(.*?);/)[1]
                var str = atob(base64[1])
                var n = str.length
                var array = new Uint8Array(n)
                while (n--) {
                    array[n] = str.charCodeAt(n)
                }
                return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], { type: type })))
            }
            var extName = base64.split(',')[0].match(/data\:\S+\/(\S+);/)
            if (extName) {
                extName = extName[1]
            } else {
                reject(new Error('base64 error'))
            }
            var fileName = getNewFileId() + '.' + extName
            if (typeof plus === 'object') {
                var basePath = '_doc'
                var dirPath = 'uniapp_temp'
                var filePath = basePath + '/' + dirPath + '/' + fileName
                if (!biggerThan(plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472', plus.runtime.innerVersion)) {
                    plus.io.resolveLocalFileSystemURL(basePath, function(entry) {
                        entry.getDirectory(dirPath, {
                            create: true,
                            exclusive: false,
                        }, function(entry) {
                            entry.getFile(fileName, {
                                create: true,
                                exclusive: false,
                            }, function(entry) {
                                entry.createWriter(function(writer) {
                                    writer.onwrite = function() {
                                        resolve(filePath)
                                    }
                                    writer.onerror = reject
                                    writer.seek(0)
                                    writer.writeAsBinary(dataUrlToBase64(base64))
                                }, reject)
                            }, reject)
                        }, reject)
                    }, reject)
                    return
                }
                var bitmap = new plus.nativeObj.Bitmap(fileName)
                bitmap.loadBase64Data(base64, function() {
                    bitmap.save(filePath, {}, function() {
                        bitmap.clear()
                        resolve(filePath)
                    }, function(error) {
                        bitmap.clear()
                        reject(error)
                    })
                }, function(error) {
                    bitmap.clear()
                    reject(error)
                })
                return
            }
            if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
                var filePath = wx.env.USER_DATA_PATH + '/' + fileName
                wx.getFileSystemManager().writeFile({
                    filePath: filePath,
                    data: dataUrlToBase64(base64),
                    encoding: 'base64',
                    success: function() {
                        resolve(filePath)
                    },
                    fail: function(error) {
                        reject(error)
                    }
                })
                return
            }
            reject(new Error('not support'))
        })
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
  • 相关阅读:
    android studio编译SDL so库
    架构师面试必备:高并发限流算法全攻略
    【Android Gradle 插件】Gradle 扩展属性 ① ( Gradle 扩展属性简介 | Gradle 自定义 task 任务示例 )
    软件设计师:03-数据库系统
    奶茶店冬天怎么提升销量 | 奶茶技术培训
    前端 WebSocket 的一些使用
    云原生之深入解析如何使用Vcluster Kubernetes加速开发效率
    【Linux系统管理】07 软件包管理 & 08 用户和权限
    Dify源码本地部署启动
    富文本文案存储翻译方案
  • 原文地址:https://blog.csdn.net/sqf251877543/article/details/127787296