如何在Vue.js和Laravel中上传数组文件?

41ik7eoe  于 2023-11-20  发布在  Vue.js
关注(0)|答案(1)|浏览(159)

我试图在Laravel和vue.js中上传多个文件,但我不知道我错过了它的实际方式。
谢谢

Vue文件

<template>
  <form @submit.prevent="handleSubmit">
    <label>Course Module PDF</label>
    <input type="file" class="form-control-file" @change="onChangeFiles" />
  </form>
</template>

<script>
export default {
  data() {
    return {
      files: [],
    };
  },
  methods: {
    handleSubmit() {
      let data = new FormData();
      data.append("files[]", this.files);

      axios.post("/add-course", data, {
    headers: {
        'Content-Type': 'multipart/form-data'
    }
  })
        .then(() => {
          this.isLoading = false;
          console.log('Success');
        })
        .catch(error => {
          console.log(error);
          
          
        }
    },
    },
    onChangeFiles(event) {
      let file = event.target.files[0];
      this.files.push(file);
    },
  },
};
</script>

字符串

控制器代码

$files = $request->files;

  if (count($files) > 0) {

      foreach ($files as $file) {
          $ext = $file->getClientOriginalExtension();
          $name = time().'-'.".".$ext;
          $upload_path = 'backend/files/';
          $upload_url = $upload_path.$name;
          $file->move(public_path($upload_path),$upload_url);
      }

  }

  return "Success";


什么都没有发生
模板截图:
http://prntscr.com/111fd8j

hwamh0ep

hwamh0ep1#

当你试图保存它在你的后端和确切地在循环中时,只需要改变fileName格式:

$upload_path = public_path('upload'); // there is no need to define variable in each loop iteration 
foreach ($request->file("files") as $file) {
        $file_name = $file->getClientOriginalName();
        $generated_new_name = time() . '-'. $file_name .'.'. $file->getClientOriginalExtension();
        $file->move($upload_path, $generated_new_name);
    }

字符串
问题是,后端覆盖了文件,因为它具有相同的名称,因为时间()函数,所以所有的文件将在同一时间创建,所有来自前端的文件将具有相同的名称,并且可以肯定的是,只有最后一个文件将被保存,所以你会认为前端只发送一个文件,但如果你试图做sizeOf($request->file(“files”)),它会给你给予已经发送的文件数量..
希望这能解决你的问题...

相关问题