【发布时间】:2021-02-05 19:18:38
【问题描述】:
我在Laravel 5.8.38中尝试实现多文件上传功能时出现数组转字符串错误 找不到任何关于它的决定
在刀片形式中,我有简单的事情:
<form class="form-horizontal" action="{{route('admin.estates.store')}}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<label for="estate_image" class="mt-4">Images</label>
<input type="file" name="estate_image[]" multiple>
<input class="btn btn-primary" type="submit" value="Сохранить">
<input type="hidden" name="created_by" value="{{Auth::id()}}">
</form>
我有店内功能:
该函数创建一个庄园(一个财产)。如果用户为其添加了一些图像,我们将这些图像添加到本地路径并添加到数据库中
如果我评论 $estate = Estate::create($request->all()); 它可以正常工作
但在这种情况下,房地产不会添加到数据库中
public function store(Request $request)
{
$estate = Estate::create($request->all());
if($request->hasFile('estate_image')) {
foreach ($request->file('estate_image') as $image) {
// do some image resize and store it on local path
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images\\' . $filename);
Image::make($image)->resize(800, 400)->save($location);
// add image info in database
$estateimage = new EstateImages();
$estateimage->image_path = $location;
$estateimage->image_alt = 'testalt';
$estateimage->save();
}
}
}
我从输入得到的数组
array:5 [▼
"name" => array:2 [▼
0 => "image1.jpg"
1 => "image2.jpg"
]
"type" => array:2 [▼
0 => "image/jpeg"
1 => "image/jpeg"
]
"tmp_name" => array:2 [▼
0 => "C:\OSPanel\userdata\php_upload\phpCB51.tmp"
1 => "C:\OSPanel\userdata\php_upload\phpCB52.tmp"
]
"error" => array:2 [▼
0 => 0
1 => 0
]
"size" => array:2 [▼
0 => 164808
1 => 58217
]
]
据了解,foreach 没有启动,但不明白为什么(试图删除 foreach 中的所有代码,并留下简单的 echo 'Hello!'; ,有同样的错误。 在 StackOverflow 中看到了同样的问题,但其中任何一个都对我有所帮助...
【问题讨论】:
-
你试过用
name="estate_image"代替name="estate_image[]"吗? -
kerbh0lz,是的,我试过了。如果
name="estate_image"它可以工作,但它只在本地路径中添加一张图像,在数据库中只添加一张图像。所以它只适用于一张图像,而不是我需要的几个(多个)。 -
你能显示 Estate 类字段的结构吗......你得到这个错误是因为你得到一个数组字段,它不能存储在你的庄园表中
-
Tanvir Ahmed,你走对了。已经找到了,并在下面的帖子中写了一个解决方案。还是谢谢!
标签: laravel laravel-5.8 multiple-file-upload