放置表格数据axios vue.js [英] PUT form-data axios vue.js

查看:68
本文介绍了放置表格数据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'
    }
})

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

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