我刚刚更新了我的用户模型与“头像”字段,所以我可以上传一张照片。 我使用了一个已经配置好的PUT方法,只是在其中添加了avatar。 在postman中,文件上传(form-data)工作得很好,但是当试图使用vue.js中的axios上传它时,它就不工作了。 我尝试了很多方法,最后一个,我尝试发送请求作为多表单数据。
async saveChanges() {
const fd = new FormData();
fd.append("id", this.$auth.user().id);
fd.append("username", this.$auth.user().username);
fd.append("email", this.user.email);
fd.append("firstName", this.$auth.user().firstName);
fd.append("lastName", this.$auth.user().lastName);
fd.append("isAdmin", this.$auth.user().isAdmin);
fd.append("password", this.user.password);
fd.append("confirmpass", this.user.confirmpass);
fd.append("avatar", this.selectedFile, this.selectedFile.name);
fd.append("_method", "put");
try {
await this.axios.put(`/users/${this.$auth.user().id}`, {
fd
}).then((res) => {
console.log(res);
});
} catch (err) {
console.error(err);
}
}
在我选择文件后,它是可用的,但我无法通过我的方法发送它。 我应该创建另一个请求只是为了更新头像还是有可能解决这个问题?
试试这个
axios.put('/users/${this.$auth.user().id', fd, {
headers: {
'Content-Type': 'multipart/form-data'
}
})