wx.chooseMessageFile在pc端微信小程序失效解决方法

项目场景:

在uniapp上驱动微信开发者工具(下图)

在手机上和微信开发者工具中(图1)都可以上传成功,

打开pc端的微信小程序

在pc端打开小程序时点击上传没反应


问题描述

提示:这里描述项目中遇到的问题:

在pc端打开小程序上传的时候发现点击上传没有反应,通过(    console.log("打印====111")    )打印步骤发现wx.chooseMessageFile方法失效

下面是代码

封装上传代码

//微信 上传文件方法  需要传入3个参数 
//count是上传文件的数量 
//extension 参数是用来指定文件类型的过滤条件,
//formData是上传文件的数据
export function wx_chooseMessageFile(type, count, extension, formData) {
	return new Promise((resolve, reject) => {
		wx.chooseMessageFile({
			type: type,
			count: count,
			extension: extension,
			//   ['.zip', '.docx', '.doc', '.pdf', 'txt', '.csv', 
            //   '.xlsx', '.ppt', '.pptx']
			success: function(res) {
				console.log("选择的文件是", res);
				let temp_path = res.tempFiles[0].path
				let name = res.tempFiles[0].name
				uni.uploadFile({
					url: process.env.VUE_APP_BASE_URL + "/file/add_file",
					filePath: temp_path,
					name: "file",
					header: {
						'system-type': 3,
						'Authorization': uni.getStorageSync('token') ?
                             "Bearer " + uni.getStorageSync('token') : ''
					},    
					formData: formData,
					success(uploadFileRes) {
						console.log("打印uploadFileRes", uploadFileRes);
						if (uploadFileRes.statusCode == 200) {
							let data_ = JSON.parse(uploadFileRes.data)
							// 将请求成功的结果返回
							resolve(data_)
						} else {
							uni.showToast({
								title: uploadFileRes.data.msg,
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						reject(err);
					}
 
				})
			}
		})
	})
}
 

下载与预览代码

wx.chooseMessageFile({
  ...
  success(res) {
    const filePath = res.tempFiles[0].path; // 获取上传成功后的文件路径
    const downloadUrl = 'https://example.com/file.mp4'; // 下载链接
    const previewUrl = 'https://example.com/image.jpg'; // 预览链接
    // 下载文件
    wx.downloadFile({
      url: downloadUrl,
      success(res) {
        const filePath = res.tempFilePath; // 下载成功后的文件路径
        // 在页面中展示下载链接
        const downloadLink = document.createElement('a');
        downloadLink.href = filePath;
        downloadLink.innerText = '下载文件';
        document.body.appendChild(downloadLink);
      }
    });
    // 预览文件
    wx.previewFile({
      url: previewUrl,
      success(res) {
        // 在页面中展示预览链接
        const previewLink = document.createElement('a');
        previewLink.href = previewUrl;
        previewLink.innerText = '预览文件';
        document.body.appendChild(previewLink);
      }
    });
  }
})


原因分析:

提示:这里填写问题的分析:

wx.chooseMessageFile只支持移动端的使用,并不支持pc端,所以在pc端打开微信小程序的时候方法wx.chooseMessageFile会失效


解决方案:

提示:这里填写该问题的具体解决方案:

1:下载第三方库

在wx.chooseMessageFile方法失效的时候有想过用原生的<input type="file"/>后来发现也不行,查后发现是因为uniapp不支持原生,所以只能求助第三方库,发现vant可以,而且vant有专门针对微信小程序开发的库 就是  Vant Weapp 然后  下载这个组件库  下载后将其解压,如下图

2:引入第三方库

在自己的uniapp项目文件中,新建一个文件夹,这个文件夹与pages文件平级(我新建的叫wxcomponents)然后再在里面新建一个文件(我新建的叫vant-weapp)然后将解压后的dist文件放到里面,如下图

3:在pages.json页面中做配置

有两个地方要做配置,但是都是在pages.json页面,如下图:

1:在与pages对象数组平级的地方新加代码

"easycom": {
      "van-(.*)": "@/wxcomponents/vant-weapp/dist/$1/index"
    },

2:在globalStyle中全局配置usingComponents引用

"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "加载中",
		"navigationBarBackgroundColor": "#fff",
		"backgroundColor": "#F8F8F8",
		"titleNView": false,
		"usingComponents": {
			//这里为方便,全局引入了所有组件,也可以在某个page下单独引用某个组件
			"van-button": "/wxcomponents/vant-weapp/dist/button/index",
			"van-uploader": "/wxcomponents/vant-weapp/dist/uploader/index"
		}
	},

3:在页面中引入使用

在页面中引入组件,然后注册组件,这样才能使用

1:引入
import vanUploader from '@/wxcomponents/vant-weapp/dist/uploader/index.js';
2:在components里面注册
components: {
			vanUploader
		},
3:html中使用


<!-- accept=""上传的类型 移动端支持所有 而pc端小程序只支持图片 这是van-uploader的短板 -->
<van-uploader 
    :accept="getAccept()"
    :fileList="fileList" 
    @after-read="(event) => afterRead(event,'identification_form')">
	<van-button type="primary">上传文件</van-button>
</van-uploader>

<style>
//样式引入
@import '@/wxcomponents/vant-weapp/dist/common/index.wxss';
</style>
4:上传方法:
// 上传类型判断 van-uploader的短板 移动端都支持 PC端小程序只支持图片
getAccept() {
	const systemInfo = uni.getSystemInfoSync();
	if (systemInfo.platform === 'android' || systemInfo.platform === 'ios') {
		// 手机端支持所有文件上传
		return '';
	} else {
		// PC端只能支持 图片上传
		return 'image';
	}
},
//上传的方法
afterRead(event,name_key) {
	let that=this;
	const { file } = event.detail;
	// 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
	wx.uploadFile({
	    url: HTTP_REQUEST_URL + '/api/upload/uploadFile', // 仅为示例,非真实的接口地址
		filePath: file.url,
		name: 'file',
		// formData: { user: 'test' },
		header: {
			// #ifdef MP
			"Content-Type": "multipart/form-data",
			// #endif
			[TOKENNAME]: 'Bearer ' + store.state.app.token
		},
		success(res) {
		    // success:res =>{//箭头函数,里面可以用this
			let result=JSON.parse(res.data);
			that.form[name_key]=result.data.url;//success不是箭头函数 用that
			// this.form[name_key]=result.data.url;//success使用 箭头函数,里面可以用this
			// const { fileList = [] } = this.data;
			// fileList.push({ ...file, url: result.data.url });
			// this.setData({ fileList });
		},
	});
},
5:查看结果

注:

vant-weapp的上传可以解决uniapp运行打包发布的微信小程序中的wx.chooseMessageFile失效的问题。但是对van-uploader 封装上传的话自己封装,这里只做vant-weapp的下载引入与使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值