繁体   English   中英

PUT 表格数据 axios vue.js

[英]PUT form-data axios vue.js

我刚刚用“头像”字段更新了我的用户 model,这样我就可以上传照片了。 我使用了一个已经配置好的 PUT 方法,并在其中添加了头像。 在 postman 文件上传(表单数据)它工作得很好,但是当尝试使用 axios 从 vue.js 上传它时它不起作用。 我尝试了很多方法,最后一种方法是尝试将请求作为多表单数据发送。

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

将您的方法作为 post 方法传递并定义放入表单数据formData.append('_method', 'PUT')

async handleSubmit() {

      let formData = new FormData();
      formData.append('image', this.file);
      formData.append('title', this.form.title);
      formData.append('_method', 'PUT')

      try {
        const response = await axios.post(`image-update/${this.$route.params.id}`, formData)

        this.$router.push('/');
        console.log(response);
      } catch (e) {
        this.error = 'Something error found !';
      }
    }

我之前在$request->all()中返回空结果的错误代码

let data = new FormData()
data.append('message', 'AnyMessage')

然后我将其更改如下,它工作正常 -

let data = "message=AnyMessage"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM