首页 > 解决方案 > 如何在 Vue.js 和 Laravel 中上传文件数组?

问题描述

我正在尝试在 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

标签: laravelvue.js

解决方案


当您尝试将文件名格式保存在后端并在循环中时,只需更改文件名格式:

$upload_path = public_path('upload'); // there is no need to define variable in each loop itteration 
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);
    }

问题是后端覆盖了文件,因为由于 time() 函数,它具有相同的名称,因此所有文件将同时创建,并且来自前端的所有文件都将具有相同的名称,并且肯定只有最后一个文件将被保存,因此您会认为前端只发送一个文件,但如果您尝试执行 sizeOf($request->file("files")) 它会给您已发送的文件数。 ..

希望这能解决您的问题...


推荐阅读