vue前端通过用methods中的upload()方法从后端获取文件id和文件名后,如何把变量传递给js
里的另一个方法submit(),从而通过表单把文件的相关数据存到数据库;


vue前端通过用methods中的upload()方法从后端获取文件id和文件名后,如何把变量传递给js
里的另一个方法submit(),从而通过表单把文件的相关数据存到数据库;


上午好☀️☀️☀️️
本答案参考ChatGPT-3.5
要在 Vue 中将 upload() 方法获取的文件 ID 和文件名传递给 submit() 方法,你需要在 upload() 方法中设置一个对象或者变量来保存这两个值,然后在适当的时候将其传递给 submit()。以下是修改后的代码:
首先,在 upload() 方法中创建一个对象或变量来存储文件信息:
methods: {
// ...
upload() {
const that = this;
uni.chooseImage({
success: function (chooseImageRes) {
const tempFilePaths = chooseImageRes.tempFilePaths;
let fileInfo = {
fileId: null, // 文件ID
fileName: null // 文件名
};
for (let i = 0; i < tempFilePaths.length; i++) {
uni.uploadFile({
url: 'http://localhost:3333/file/upload',
filePath: tempFilePaths[i],
method: 'post',
name: 'file',
success: function (uploadFileRes) {
const response = JSON.parse(uploadFileRes.data);
fileInfo.fileId = response.id;
fileInfo.fileName = response.fileName;
console.log("文件ID:", fileInfo.fileId);
console.log("文件名:", fileInfo.fileName);
// 将文件信息对象传递给submitForm方法
that.submitForm(fileInfo);
uni.showToast({
title: '上传成功',
icon: 'none',
duration: 2000
});
},
fail: function () {
console.error('上传失败');
}
});
}
},
fail: function () {
console.error('选择图片失败');
}
});
},
// ...
}
接下来,在 submitForm 方法中接收并使用 fileInfo 对象:
async submitForm(fileInfo) {
// 确保fileInfo对象已包含文件ID和文件名
if (fileInfo.fileId && fileInfo.fileName) {
try {
await this.$http.post('/qz/save', {
userId: '111',
xm: this.form.name,
gw: this.form.gw,
nl: this.form.age,
xl: this.form.x1,
xb: this.form.sex,
j1: this.form.j1,
lxfs: this.form.phone,
jlFileName: fileInfo.fileName,
fileId: fileInfo.fileId // 在这里添加文件ID
}).then(res => {
alert("发送成功!!!");
}).catch(err => {
alert("发送失败!!!");
});
} catch (err) {
console.error('提交失败:', err);
}
} else {
console.error('文件信息不完整');
}
}
这样,upload() 方法就会在文件上传成功后将文件ID和文件名传递给 submitForm() 方法。记得检查文件信息是否齐全再进行提交操作。