Laravel:多文件上传,Input::hasFile(key) 始终为 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24761478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Multiple File Upload, Input::hasFile(key) always false
提问by Azeruel
i generated a multiple upload form with the former generator tool from https://github.com/Anahkiasen/former.
我使用来自https://github.com/Anahkiasen/former的前生成器工具生成了一个多重上传表单。
{{ Former::files('file')->accept('image')->required(); }}
that results in
这导致
<input multiple="true" accept="image/*" required="true" id="file[]" type="file" name="file[]">
After I've submit the form Ive figured out that Input::hasFile('file')
always returns false whilst Input:has('file') returns true
.
在我提交表单后,我发现它Input::hasFile('file')
总是返回 false while Input:has('file') returns true
。
What i've tried until now:
到目前为止我尝试过的:
Log::info(Input::file('file')); <-- empty
日志::信息(输入::文件('文件')); <-- 空
foreach(Input::file('file') as $file) <-- Invalid argument supplied for foreach()
Log::info("test");
if(Input::has('file'))
{
if(is_array(Input::get('file')))
foreach ( Input::get('file') as $file)
{
Log::info($file); <-- returns the filename
$validator = Validator::make( array('file' => $file), array('file' => 'required|image'));
if($validator->fails()) {
...
}
}
}
Of course, the validator always fails cause Input::get('file') does not return a file object. How do I have to modify my code to catch the submited files?
当然,验证器总是失败,因为 Input::get('file') 不返回文件对象。我如何修改我的代码以捕获提交的文件?
回答by Azeruel
Thanks for the help, the answer from Kestutis made it clear. The common way to define a file form in Laravel is
感谢您的帮助,Kestutis 的回答说得很清楚。在 Laravel 中定义文件表单的常用方法是
echo Form::open(array('url' => 'foo/bar', 'files' => true))
This Options sets the proper encryption type with enctype='multipart/form-data'.
此选项使用 enctype='multipart/form-data' 设置正确的加密类型。
With the laravel form builder "Former" you have to open the form with
使用 Laravel 表单构建器“Former”,您必须使用以下命令打开表单
Former::open_for_files()
After that u can validate the form in the common way.
之后,您可以以通用方式验证表单。
if(Input::hasFile('files')) {
Log::info(Input::File('files'));
$rules = array(
...
);
if(!array(Input::File('files')))
$rules["files"] = 'required|image';
else
for($i=0;$i<count(Input::File('files'));$i++) {
$rules["files.$i"] = 'required|image';
}
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
{
return ...
}
else {
// everything is ok ...
}