我遵循了以下指南https://github.com/yiisoft/yii2/blob/master/docs/guide/input-file-upload.md,但没有上传文件。下面是我的配置
_form
这是一个for循环所以我可以得到一组不同的记录。
<?= $form->field(new UploadForm , "[$count]file")->fileInput()->label(false) ?>
查看
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>...
控制器
if(isset(Yii::$app->request->post()['Factsheets'])){
for($i=0 ; $i < count(Yii::$app->request->post()['Factsheets']); $i++) {
//Yii::error(print_r(Yii::$app->request->post()['Factsheets'][$i],true));
if(!empty(Yii::$app->request->post()['UploadForm'][$i]['file'])){
$file = new UploadForm();
$file->file = UploadedFile::getInstance(Yii::$app->request->post()['UploadForm'][$i], 'file');
if ($file->file && $file->validate()) {
$file->file->saveAs('uploads/' . $file->file->baseName . '.' . $file->file->extension);
}
}
}
}
发布日志
[Factsheets] => Array
(
[0] => Array
(
[type] => image
[factsheet_id] => 1185
[path] => ../public/filespool/2/289/Pelotas_Reprocessing.jpg
)
[1] => Array
(
[type] => tech_paper
[factsheet_id] => 1433
[path] => ?basin=pelotas
)
[2] => Array
(
[type] => factsheet
[factsheet_id] => 1844
[path] => ../public/filespool/2/289/Pelotas_Reprocessing.pdf
)
)
[UploadForm] => Array
(
[0] => Array
(
[file] =>
)
[1] => Array
(
[file] =>
)
[2] => Array
(
[file] =>
)
)
我现在在帖子日志中注意到以下内容。我该如何构建它?
$_FILES = [
'UploadForm' => [
'name' => [
0 => [
'file' => 'Destin_Dome.jpg'
]
1 => [
'file' => ''
]
2 => [
'file' => 'Pelotas_Reprocessing.pdf'
]
]
'type' => [
0 => [
'file' => 'image/jpeg'
]
1 => [
'file' => ''
]
2 => [
'file' => ''
]
]
'tmp_name' => [
0 => [
'file' => '/tmp/phpoPgbJ9'
]
1 => [
'file' => ''
]
2 => [
'file' => ''
]
]
'error' => [
0 => [
'file' => 0
]
1 => [
'file' => 4
]
2 => [
'file' => 1
]
]
'size' => [
0 => [
'file' => 1129373
]
1 => [
'file' => 0
]
2 => [
'file' => 0
]
]
]
]
似乎验证失败但是我能够复制如下:
if(!empty($_FILES['UploadForm']['tmp_name']['file'])){
copy($_FILES['UploadForm']['tmp_name']['file'],"/tmp/".$_FILES['UploadForm']['name']['file']);
}
fileUpload model
public $file;
public $image;
public $factsheet;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file','maxFiles' => 10],
[['image'], 'file','extensions' => 'gif, jpg'],
[['factsheet'], 'file','checkExtensionByMimeType' => false,'extensions' => 'pdf'],
];
}
答案 0 :(得分:1)
我可能错了,但我认为问题出在您的控制器中:您的模型规则适用于多个文件上传和您的表单字段,但在控制器中您将$model->file
设置为单个UploadedFile
实例。这就是您的验证不起作用的原因。我无法给出你的建议(改变控制器或模型规则),因为我不清楚你在这里做什么。看起来您正在从单个文件上传字段创建多个模型...