使用Laravel 8和Jetstream上传文件时“调用数组上的成员函数store()”- Vue & Intertia.js

xxls0lw8  于 2022-12-23  发布在  Vue.js
关注(0)|答案(2)|浏览(144)

我从vue文件中的表单上载图像时遇到问题。我尝试了几种方法,但似乎文件设置不正确。

  • 我在表单标记中设置了“enctype=“multipart/form-data
  • 下面是我的输入元素:

〈input @change=“onFileChange”类型=“文件”接受=“图像/*”类=“表单控件”名称=“文件”ID=“文件”描述的对象=“帮助ID”占位符=“上传文件”/〉

  • 下面是我的数据对象和发送数据的方法:
data() {
      return {
    editMode: false,
    professionaldevelopmentitems: [],
    professionaldevelopmentitem: {
      domain: 1,
      domaincategory: 1,
      title: "",
      dateofpd: "",
      location: "",
      lengthofpd: "",
      facilitatorname: "",
      facilitatorcredentials: "",
      reflection: "",
      file: "",
    },
  };
},
methods: {
  onFileChange(e) {
    alert(e.target.files[0]);
    alert(e.target.files[0].name);
    var files = e.target.files || e.dataTransfer.files;
    if (!files.length)
      return;
    this.professionaldevelopmentitem.file = e.target.files[0];
    alert(this.professionaldevelopmentitem.file);
  },    
  async addProfessionalDevelopmentItem() {
    document.getElementById("pdForm").reset();
    this.editMode = false;
    const res = await axios.post(
      "/api/professionaldevelopmentitems",
      this.professionaldevelopmentitem
    );

    if (res.status === 201) {
      Toast.fire({
        icon: "success",
        title: res.data,
      });
      document.getElementById("pdForm").reset();
      $("#manageProfessionalDevelopmentItem").modal("hide");
      Fire.$emit("modifiedPDItem");
    }
  },
  async editProfessionalDevelopmentItem(data) {
    this.professionaldevelopmentitem = Object.assign({}, data);
    this.editMode = true;
  },
  async updateProfessionalDevelopmentItems(data) {
    const res = await axios.put(
      `/api/professionaldevelopmentitems/${data.id}`,
      this.professionaldevelopmentitem
    );

    if (res.status === 200) {
      Toast.fire({
        icon: "success",
        title: res.data,
      });
      document.getElementById("pdForm").reset();
      $("#manageProfessionalDevelopmentItem").modal("hide");
      Fire.$emit("modifiedPDItem");
      this.editMode = false;
    }
  },

我在控制器中接收数据并尝试存储文件:
公共函数更新(请求$request,$id){

dd($request->all());

$this->validate($request, [
    'title' => ['required'],
    'dateofpd' => ['required'],
    'lengthofpd' => ['required'],
    'location' => ['required']
]);

$path = $request->file('filename')->store('uploads');

$pditem = ProfessionalDevelopmentItem::find($id);
$pditem->domain = $request->domain;
$pditem->domaincategory = $request->domaincategory;
$pditem->title = $request->title;
$pditem->dateofpd = $request->dateofpd;
$pditem->lengthofpd = $request->lengthofpd;
$pditem->location = $request->location;
$pditem->facilitatorname = $request->facilitatorname;
$pditem->facilitatorcredentials = $request->facilitatorcredentials;
$pditem->certificategranted = $request->certificategranted;
$pditem->certificateexpires = $request->certificateexpires;
$pditem->certificateexpiration = $request->certificateexpiration;
$pditem->reflection = $request->reflection;
$pditem->nameofinstitution = $request->nameofinstitution;
$pditem->coursename = $request->coursename;
$pditem->coursecode = $request->coursecode;
$pditem->hoursofinstruction = $request->hoursofinstruction;
$pditem->creditgranted = $request->creditgranted;
$pditem->bookname = $request->bookname;
$pditem->bookauthor = $request->bookauthor;
$pditem->bookyear = $request->bookyear;
$pditem->bookpublisher = $request->bookpublisher;
$pditem->otherdescription = $request->otherdescription;
$pditem->filename = $path;

$pditem->save();

return response('Successfully Updated the Professional Development Item.', 200);

}
返回的响应是在尝试存储文件时该行出现错误:

"message": "Call to a member function store() on array",
"exception": "Error",

任何关于我做错了什么的想法都将不胜感激。

q9rjltbz

q9rjltbz1#

尝试在FormData中发送上传的文件,在Vue组件中定义一个方法来准备FormData,其中包含所有要通过 AJAX 发送到服务器的数据

prepareFormData() {
    let data = new FormData;

    Object.keys(this.professionaldevelopmentitem).forEach(
        key => data.append(key, this.professionaldevelopmentitem[key]
    );

    return data;
}

然后使用此方法获取FormData并将其作为数据发送到addProfessionalDeveloomentItemupdataProfessionalDevelopmentItems中的服务器

async addProfessionalDevelopmentItem() {
    document.getElementById("pdForm").reset();
    this.editMode = false;
    const res = await axios.post(
      "/api/professionaldevelopmentitems",
      this.prepareFormData()
    );

    if (res.status === 201) {
      Toast.fire({
        icon: "success",
        title: res.data,
      });
      document.getElementById("pdForm").reset();
      $("#manageProfessionalDevelopmentItem").modal("hide");
      Fire.$emit("modifiedPDItem");
    }
  },
  

  async updateProfessionalDevelopmentItems(data) {
    const res = await axios.put(
      `/api/professionaldevelopmentitems/${data.id}`,
      this.prepareFormData()
    );

    if (res.status === 200) {
      Toast.fire({
        icon: "success",
        title: res.data,
      });
      document.getElementById("pdForm").reset();
      $("#manageProfessionalDevelopmentItem").modal("hide");
      Fire.$emit("modifiedPDItem");
      this.editMode = false;
    }
}

然后您应该在关键文件$request-〉file('file')下的$request中获得上传的文件

lmvvr0a8

lmvvr0a82#

这个错误意味着$request->file('filename')返回数组,在我们的例子中,这是因为我们允许用户一次提交2个文件:

<form action="/upload" method="post" enctype="multipart/form-data">
    @csrf
    <input type="file" name="filename[]"><br>
    <input type="file" name="filename[]"><br>
    <input type="submit">
</form>

为了在Laravel 9中解决这个问题,我们在控制器的方法中添加了变量的类型检查:

public function upload(Request $request)
{
    $file = $request->file('filename');

    if (is_array($file)) {
        foreach ($file as $item) {
            $item->store('uploads');
        }
    } else {
        $file->store('uploads');
    }

    // ...
}

相关问题