文件图片预览方式:
利用微信自带的wx.downloadFile() + wx.openDocument()
uni-app官网 | uni.uploadFile(OBJECT) 详解
https://uniapp.dcloud.net.cn/api/request/network-file.html#downloadfile
uni-app官网 | uni.uni.openDocument(OBJECT)详解
https://uniapp.dcloud.net.cn/api/file/file.html#opendocument
代码如下
读取文件/文件夹警告出现原因:
以上警告是由于微信小程序的安全策略导致的。微信小程序对于网络请求和文件读取都有一些限制,其中包括白名单机制。如果你的小程序中的文件不在白名单中,那么在真机上可能无法读取。
解决方案:
我们先使用uni.downloadFile把后台接口或者本地的PDF以及其他格式转为获取到本地临时路径。然后再使用uni.openDocument就可以了。
源码如下:
<view class="" v-for="(item, index) in Lists" :key="index"> <view class="flex"> <view class="u-flex" @click="Preview(item)">{{ item.name }}</view> </view></view> // 文件类型识别,用正则去识别不同文件类型,然后对应不同文件类型去做不同操作 Preview(item) { console.log(item); // 定义图片类型的正则表达式 const imageRegex = /(/.jpg|/.jpeg|/.png)$/i; // 定义文档类型的正则表达式 const docRegex = /(/.doc|/.docx|/.pdf)$/i; // // 定义其他文件类型的正则表达式 const othersRegex = /(/.txt|/.csv|/.xlsx)$/i; // 利用正则表达式判断文件类型 if (imageRegex.test(item.name)) { console.log("图片类型"); this.lookImage(item.url) //预览图片 } else if (docRegex.test(item.name)) { console.log("文档类型"); this.lookFile(item.url) //预览文件 } else if (othersRegex.test(item.name)) { console.log("其他文件类型"); } else { uni.showToast({ title: `未知文件类型`, icon: 'none', duration: 2000 }) } },// 预览图片 lookImage(url) { let imgArray = []; imgArray[0] = url uni.previewImage({ current: 0, urls: imgArray }) },//预览文件//此处的参数url为uni.uploadFile上传文件,返回的永久地址 lookFile(url) { console.log('预览文件的url:',url) uni.downloadFile({ url:url, success:function(res){ if(res.statusCode === 200){ console.log("临时路径",res.tempFilePath) let filePath = res.tempFilePath //调用uni.openDocument打开文件 uni.openDocument({ filePath: filePath, success: function (res) { console.log("打开文档成功"); }, fail: function (res) { console.log("uni.openDocument,fail"); console.log(res) }, complete: function (res) { console.log("uni.openDocument,complete"); console.log(res) } }); } }, fail:function(err){ console.log('文件下载失败',err) } }) },














