uniapp上传文件使用uni.uploadFile,如果直接一次性在success里完成会导致页面自动刷新,特别是添加了本页面有onshow()方法,上传完会自动调用onshow()方法。
建议使用官方的方式分成两个方法处理:
async afterRead(event) {
let fileListLen =this.fileList.length;
for (let i = 0; i < event.file.length; i++) {
that.uploadPromise(event.file[i]).then(result=>{
let item = this.fileList[fileListLen]//当前文件
item.status ="success"
item.message =""
item.url =result
fileListLen++
})
}
},
async uploadPromise(myfile: { url: any; name: any; type: any; }) {
let accessToken = uni.getStorageSync('access-token')
return new Promise((resolve, reject) => {
console.log(myfile.type)
uni.uploadFile({//后台读取不到文件名
url: env.baseUrl+'api/Problem/uploadAttachs',
//file:myfile,//浏览器环境只能用单文件方式上传
filePath:myfile.url,//app环境能用多文件或本地文件路径方式上传
name:'file',
header:{
'ignoreCancelToken': true,
'Authorization':`Bearer ${accessToken}`
},
formData:{
file: myfile,
fileName: myfile.name,
fileType: myfile.type
},
timeout:180000,
success: (res) => {
console.log('上传结果'+res.data)
let resdata = JSON.parse(res.data);
setTimeout(() => {
let fileurl = resdata.result?resdata.result.url:'';
resolve(fileurl);
}, 1000);
},
fail: (error) => {
reject(error);
}
});
});
}
后端返回的文件相对路径,再保存方法中处理一起提交。但莫名奇妙的出现提交完成后直接退出的情况,一搜索啥都找不到。ai提示使用事件阻止event.preventDefault();但这里似乎不合适。
真机测试发现就是uni.showToast方法的问题。
updateProblem(reqdata).then(res => {
if (res.code == 200) {
uni.navigateBack({
delta: 1 // 返回上一级页面
});
//与返回上一页一起使用弹窗会导致直接退出app
// uni.showToast({
// title: '编辑成功',
// icon: 'success',
// duration: 2000
// });
}
else{
uni.showToast({
title: '编辑失败',
icon: 'warning',
duration: 2000
});
}
}).catch(()=>{
uni.showToast({
title: '编辑保存异常,请稍后再试!',
icon: 'warning',
duration: 2000
});
})
真的很奇怪,提交完成后返回上一页就不能提示了。