uniapp下载文件为blob怎么打开
时间: 2023-11-28 10:06:19 浏览: 549
在uniapp中,可以使用uni.previewImage()方法来预览图片,可以使用uni.openDocument()方法来打开其他类型的文件。
以下是实现代码:
```
uni.downloadFile({
url: 'your download url',
success: (res) => {
if (res.statusCode === 200) {
uni.getFileSystemManager().readFile({
filePath: res.tempFilePath,
encoding: 'base64',
success: (data) => {
let base64 = 'data:image/jpeg;base64,' + data.data
let blob = this.base64ToBlob(base64)
console.log(blob)
if (blob.type.indexOf('image') !== -1) {
uni.previewImage({
urls: [base64]
})
} else {
uni.openDocument({
filePath: res.tempFilePath
})
}
}
})
}
}
})
// base64转blob
base64ToBlob(base64) {
let arr = base64.split(',')
let type = arr[0].match(/:(.*?);/)[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: type })
}
```
这样就可以根据文件类型来选择预览图片或打开其他类型的文件了。