一、选择文件并上传,典型实现
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 选择一个文件
-
count: 1
:最多选择 1 个文件 -
type: "file"
:选择普通文件(可以是任意类型) -
res.tempFiles
:一个数组,包含选择的文件信息 -
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 将选择的文件上传到指定的地址
-
url: "【上传地址】"
:上传文件的服务器地址 -
filePath
:文件的临时路径(从wx.chooseMessageFile
获取) -
name
:文件对应的 key,服务器通过该 key 获取文件 -
success
:上传成功时触发,res 包含服务器返回的数据 -
fail
:上传失败时触发,err 包含错误信息
二、选择文件并上传,结合 Vant Weapp 实现
1、引入 Vant Weapp
- Vant Weapp 官网地址:
https://vant-ui.github.io/vant-weapp/#/quickstart
-
安装 Vant Weapp:
npm i @vant/weapp -S --production
-
修改
app.json
:将app.json
中的"style": "v2"
去除 -
点击 【工具】
->点击 【构建 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);
// 更多处理...
},
});
},
});