php - foreach 语句导致多文件上传中未定义的变量 fileNameToStore
问题描述
我试图上传多个文件,所以我尝试稍微修改代码。但每次我添加 foreach($request->file('image') as $file)。我总是收到有关未定义变量的错误。我在下面附上了我的控制器代码,知道如何解决这个问题并进行多文件上传吗?
if($request->hasFile('image'))
{
foreach($request->file('image') as $file)
{
$filenameWithExt =$request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename. '_'.time().'.'.$extension;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
}
}
$post = new Post;
$post->image = $fileNameToStore;
$post->save();
return redirect('/dashboard')->with('success', 'Post Created!');
这是 create.blade.php
@extends('layouts.app')
@section('content')
<h1>Upload Images</h1>
{!! Form::open(['action' => 'PostsController@store', 'method'=> 'POST','enctype'=>'multipart/form-data'])!!}
<div class="form-group">
{{Form::file('image',['multiple'=>'true', 'files'=>'true'])}}
</div>
{{Form::submit('Submit',['class' => 'btn btn-success'])}}
{!!Form::close()!!}
解决方案
如果我正确理解你。尝试添加fileNameToStore
变量foreach
:
$errors = [];
$post = new Post;
if ($request->hasFile('cover_image')) {
foreach ($request->file('cover_image') as $file) {
$filenameWithExt =$request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename. '_'.time().'.'.$extension;
$path = $request->file('image')->move('public/images', $fileNameToStore);
$post->cover_image = $fileNameToStore;
}
if (! fileNameToStore) {
$errors[] = false;
}
if (count($errors) > 0) {
return redirect('/dashboard')->with('error', 'Somthing went wrong!');
}
}
$post->save()
return redirect('/dashboard')->with('success', 'Post Created!');
希望能帮到你。PS 替换image
为cover_image
.
推荐阅读
- docker - 我可以使用/构建自定义创建的 docker 镜像来创建另一个镜像吗?
- c++ - 在没有管理员权限的情况下安装 C++ 编译器
- r - 多个 gganimate 并排绘制
- java - 无法将 groovy 文件添加到源文件夹
- javascript - 无法创建所需的 UI
- redis - Jackson2HashMapper 不使用 Flatten=True 序列化日期
- python - 我可以逃避这个错误 Traceback(最近一次通话最后一次):文件“
",第 1 行,在 文件 ” ",第 2 行,在 data_entry 中 - python - 如何让这个功能更容易测试?
- php - 提交表单时,会话数据会变得很多
- php - PhpStorm 是否可以根据更改的项目文件夹结构自动更改命名空间和用途?