PUT 表单数据 axios vue.js [英] PUT form-data axios vue.js

查看:32
本文介绍了PUT 表单数据 axios vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚用头像"更新了我的用户模型字段,以便我可以上传照片.我使用了一个已经配置好的 PUT 方法,只是添加了头像.在邮递员中,文件上传(表单数据)工作正常,但是当尝试使用 vue.js 中的 axios 上传它时,它不起作用.我尝试了很多方法,最后一个,我尝试将请求作为多表单数据发送.

I just updated my User model with "avatar" field so I can upload a photo. I used a PUT method already configured and just added avatar to it. In postman the file upload (form-data) it works just fine, but when trying to upload it using axios from vue.js it doesn't work. I tried in many ways, the last one, I tried to send the request as multi form data.

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);
      }
}

选择文件后,它可用,但我无法通过我的方法发送它.我应该创建另一个请求来更新头像还是可以解决这个问题?

After i choose the file, it is available, but I am unable to send it trough my method. Should i create another request just for updating the avatar or is it possible to solve this?

推荐答案

试试这个

axios.put('/users/${this.$auth.user().id', fd, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

这篇关于PUT 表单数据 axios vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆