laravel - 如何在 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";
什么都没有发生
模板截图:
解决方案
当您尝试将文件名格式保存在后端并在循环中时,只需更改文件名格式:
$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")) 它会给您已发送的文件数。 ..
希望这能解决您的问题...
推荐阅读
- python - 如何在 django 中将表单相互连接?
- javascript - 如何为每两个元素映射以进行反应?
- pandas - 创建具有指定参数的图形 Pandas
- c - 如何将自定义 *.so 文件包含到 CMAKE?
- c# - 使用 Entity Framework Core 按类型未知的 JsonDocument 属性分组
- java - 如何创建一个启动 java 应用程序处理其依赖项的包装脚本?
- java - Sharedpreference.edit() 在 JUnit 测试 + Mockito 中给出 NullPointerException
- android - 为什么让移动应用程序向 ELK 发送崩溃日志不流行
- pytorch - 在 PyTorch 中,逐行与矩阵中每隔一行的元素批量矩阵乘法
- python - 如何使用 youtube-dl 在不下载的情况下获取有关视频的信息