【问题标题】:How to POST correctly a form that have data and files with VueJS, Axios and Laravel?如何使用 VueJS、Axios 和 Laravel 正确发布包含数据和文件的表单?
【发布时间】:2021-04-23 11:33:48
【问题描述】:

我作为 VueJS 和 Laravel 的初学者在这里发帖。经过数小时的搜索,我遇到了一个无法自行解决的问题。

我想知道如何正确地发送和取回表单的输入(复杂的数据和文件)。

这里是表单的提交方法:

onSubmit: function () {
  var formData = new FormData();
  formData.append("data", this.model.data);
  formData.append("partData", this.model.partData);
  if (this.model.symbolFile != null) {
    formData.append("symbolFile", this.model.symbolFile);
  }
  if (this.model.footprintFile != null) {
    formData.append("footprintFile", this.model.footprintFile);
  }
  axios
    .post("/api/updatecomponent", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })
    .then((res) => {
      // do something with res
      // console.log(res);
    })
    .catch((err) => {
      /* catch error*/
      console.log(err);
    });
},

变量 Data 和 PartData 包含多个字符串字段,这些字段将存储在我数据库的不同表中。例子 : 数据 { 字符串值, 字符串公差, 字符串电源 }

这里是Controller在服务端的方法:

public function updateComponent(Request $req)
{
   $data = $req->input('data');
   $partData = $req->input('partData');
   $symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
   $footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
   // etc...
}

我能够获取文件,一切正常,我可以存储和阅读它们:)

但是,问题是我无法正确取回我的数据或 PartDat。 当我这样做时:

dd($partData);

我在控制台中得到了结果:

"[object Object]"

我几乎可以肯定我没有正确使用 FormData,但是经过数小时的搜索,我找不到应该将 Data 和 PartData 提供给 FormData 的好方法。

在我添加 FormData 以支持文件上传之前,我的代码在 Data 和 PartData 上运行良好:(

感谢您的帮助:)

【问题讨论】:

  • 嗨,你快到了,你做了内容类型多部分/表单数据,但你应该以稍微不同的方式添加文件,这个答案可能会提供详细信息:@987654321 @
  • 试试json_decode($req->input('data'))
  • @Tpojka,谢谢!你没看错

标签: laravel vue.js axios


【解决方案1】:

这是我的工作代码:

客户端:

var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
  .post(url, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  })
  .then((res) => {
    // do something with res
    // console.log(res);
  })
  .catch((err) => {
    /* catch error*/
    console.log(err);
  });

服务器端:

public function createComponent(Request $req)
{
    $subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)        
    $data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}

我希望它会帮助其他人:)

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2018-12-25
    • 2021-02-16
    • 2017-11-07
    • 1970-01-01
    相关资源
    最近更新 更多