[uniapp小程序][文件和图片预览方法][读取文件/文件夹警告] 无法读取 文件或文件夹不在白名单中, 上传时会被忽略, 在真机上可能无法读取

文件图片预览方式:

利用微信自带的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)
			}
		})
	},


 

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值