微信小程序 - 选择文件并上传(典型实现、结合 Vant Weapp 实现)

一、选择文件并上传,典型实现

wx.chooseMessageFile({
    count: 1,
    type: "file",
    success(res) {
        const tempFilePath = res.tempFiles[0].path;
        console.log("选择的文件路径:" + tempFilePath);

        wx.uploadFile({
            url: "【上传地址】",
            filePath: tempFilePath,
            name: "file",
            success(res) {
                console.log("上传完成", res);
                
                // 更多处理...
            },
            fail(err) {
                console.error("上传失败", err);
            
            	// 更多处理...
            },
        });
    },
});
1、选择文件
wx.chooseMessageFile({
    count: 1,
    type: "file",
    success(res) {
        const tempFilePath = res.tempFiles[0].path;
        console.log("选择的文件路径:" + tempFilePath);

        ...
    },
});
  • 通过 wx.chooseMessageFile API 选择一个文件
  1. count: 1:最多选择 1 个文件

  2. type: "file":选择普通文件(可以是任意类型)

  3. res.tempFiles:一个数组,包含选择的文件信息

  4. res.tempFiles[0].path:文件的临时路径,用于后续上传

2、上传文件
wx.uploadFile({
    url: "【上传地址】",
    filePath: tempFilePath,
    name: "file",
    success(res) {
        console.log("上传完成", res);

        // 更多处理...
    },
    fail(err) {
        console.error("上传失败", err);

        // 更多处理...
    },
});
  • 通过 wx.uploadFile API 将选择的文件上传到指定的地址
  1. url: "【上传地址】":上传文件的服务器地址

  2. filePath:文件的临时路径(从 wx.chooseMessageFile 获取)

  3. name:文件对应的 key,服务器通过该 key 获取文件

  4. success:上传成功时触发,res 包含服务器返回的数据

  5. fail:上传失败时触发,err 包含错误信息


二、选择文件并上传,结合 Vant Weapp 实现

1、引入 Vant Weapp
  • Vant Weapp 官网地址:https://vant-ui.github.io/vant-weapp/#/quickstart
  1. 安装 Vant Weapp:npm i @vant/weapp -S --production

  2. 修改 app.json:将 app.json 中的 "style": "v2" 去除

  3. 点击 【工具】 -> 点击 【构建 npm】

2、具体实现
  • index.json
{
	"usingComponents": {
		"van-uploader": "@vant/weapp/uploader/index"
	}
}
  • index.html
<van-uploader file-list="{{poorFileList}}" max-count="1" bind:after-read="afterReadHandle" />
  • index.js
Page({
	data: {
		myFileList: [],
	},

	afterReadHandle(event) {
		const file = event.detail.file;
		const tempFilePath = file.tempFilePath;
		console.log("选择的文件路径:" + tempFilePath);

		wx.uploadFile({
			url: `【上传地址】`,
			filePath: tempFilePath,
			name: "file",
			success: (res) => {
                console.log("上传完成", res);

				this.setData({
					poorFileList: [
						{
							...file,
							url: 【这里从 res 中取出图片地址】,
						},
					],
				});
                
                // 更多处理...
			},
			fail(err) {
				console.error("上传失败", err);
                
                // 更多处理...
			},
		});
	},
});
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值