小程序中上传文件时无法获取file对象,只能获取path临时路径
我们可以使用 wx.chooseMessageFile和wx.uploadFile实现上传文件至服务器
wx.chooseMessageFile({ // 只能选取微信聊天框中的文件
count: 1, // 最多选择一个文件
type: "file", // 选择文件类型
success: function (res) {
// 获取文件的本地临时文件路径
const tempFiles = res.tempFiles[0];
if (tempFiles.name.indexOf(".pdf") === -1) {
uni.showToast({
icon: "none",
title: "请选择pdf文件上传",
});
} else {
uni.showLoading({
title: "正在上传",
});
wx.uploadFile({
url: `${baseURL}/rfs/chunkUploadByMobile`, //服务器地址
filePath: tempFiles.path, //文件临时路径
name: "file",
header: {
Authorization: getToken(),
"Content-Type": "multipart/form-data",
},
formData: {
docName: tempFiles.name,
},
success: (res) => {
// 上传成功执行
uni.hideLoading();
},
fail: (error) => {
uni.hideLoading();
console.log(error);
},
});
}
},
});