Hy,我无法上传yii2中的文件。 当我尝试上传文件时,它不会上传到服务器上,也无法通过验证。
print_r($ _ FILES,true) - 为空。 在debuger中没有错误。
这是我的代码:
模型:
class Model extends \yii\db\ActiveRecord
{
public $files;
public function rules()
{
return [
[['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'doc, docx',
'maxFiles' => 4],
}
}
public function uploadFiles(){
if($this->validate()){
foreach($this->files as $file){
$path = 'upload/docs/' . $file->baseName . '.' . $file->extension;
$file->saveAs($path);
@unlink($path);
}
return true;
}else{
return false;
}
}
控制器:
public function actionCreate()
{
$model = new Model();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->files = UploadedFile::getInstances($model, 'files');
$model->uploadFiles();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
查看:
_form.php
<?php $form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'],
]); ?>
<?php echo $form->field($model, 'files[]')->fileInput(['multiple' => true]) ?>