【问题标题】:PUT form-data axios vue.jsPUT 表单数据 axios vue.js
【发布时间】:2020-10-13 13:25:09
【问题描述】:

我刚刚用“头像”字段更新了我的用户模型,这样我就可以上传照片了。我使用了一个已经配置好的 PUT 方法,并在其中添加了头像。在邮递员中,文件上传(表单数据)工作得很好,但是当尝试使用来自 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);
      }
}

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

【问题讨论】:

    标签: javascript node.js vue.js axios


    【解决方案1】:

    将您的方法作为 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 !';
          }
        }
    

    【讨论】:

    • 谢谢这对我有用
    【解决方案2】:

    试试这个

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

    【讨论】:

    • 嘿,试过了。还是行不通。我也试图通过这个低谷配置
    • 您写道,您无法发送带有文件的请求。你遇到过什么样的问题?你有没有发现任何异常?
    • 不,它没有抛出任何错误。试试 { await this.axios.put(/users/${this.$auth.user().id}, fd, { headers: { "Content-Type": "multipart/form-data" } }).then((res) => { console.log(res) ; }); } 捕捉(错误){ 控制台.错误(错误);但我也没有在控制台中得到任何资源。在邮递员中,我可以使用表单数据,但是当从 vue js 尝试时,它不会抛出任何错误,我正在正确获取我的文件,我无法弄清楚我错过了什么
    • 我在正文中发送数据
    • 好吧,当您发送请求时,您会在 DevTool 的网络选项卡上看到什么响应。有哪些状态和响应对象?
    猜你喜欢
    • 2022-01-05
    • 2021-10-16
    • 2019-03-07
    • 2020-12-04
    • 2019-04-25
    • 2020-03-05
    • 2019-11-20
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多