使用ajax中的kartik yii2扩展程序执行文件上传
这是一个法院系统的实施,案件可以有很多证据,一个上传它们
模型 案例代码:
public function rules()
{
return [
[['ref_no', 'case_description', 'raised_on', 'status', 'raised_by', 'updated_on', 'case_type'], 'required'],
[['raised_on', 'updated_on'], 'safe'],
[['ref_no', 'status', 'raised_by', 'case_type'], 'string', 'max' => 100],
[['case_description'], 'string', 'max' => 300]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'ref_no' => 'Ref No',
'case_description' => 'Case Description',
'raised_on' => 'Raised On',
'status' => 'Status',
'raised_by' => 'Raised By',
'updated_on' => 'Updated On',
'case_type' => 'Case Type',
];
}
public function getEvidences()
{
return $this->hasMany(Evidence::className(), ['case_ref' => 'ref_no']);
}
证据模型代码:
public function rules()
{
return [
[['case_ref', 'saved_by', 'saved_on', 'evidence_type'], 'required'],
[['saved_on'], 'safe'],
[['path'], 'safe'],
[['case_ref', 'saved_by'], 'string', 'max' => 100],
[['evidence_type'], 'string', 'max' => 50],
[['path'], 'file']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'case_ref' => 'Case Ref',
'saved_by' => 'Saved By',
'saved_on' => 'Saved On',
'id' => 'ID',
'evidence_type' => 'Evidence Type',
'path' => 'Path',
];
}
public function getCaseRef()
{
return $this->hasOne(Cases::className(), ['ref_no' => 'case_ref']);
}
在我的控制器动作中创建(案例控制器) 代码:
public function actionCreate()
{
$model = new Cases();
$evidence = new Evidence();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->ref_no]);
}
else {
return $this->render('profile', [
'model' => $model,'evidence'=>$evidence,
]);
}
}
该视图是由create呈现的配置文件 代码:
<?php $form = ActiveForm::begin([
'options' => ['enctype'=>'multipart/form-data']
]); ?>
<?php echo $form->field($evidence, 'path')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*','multiple' => true],
'pluginOptions' => [
'browseIcon' => '<i class="glyphicon glyphicon-camera"></i> ',
'showPreview' => true,
'showCaption' => true,
'showRemove' => true,
'showUpload' => true,
'filename'=>'kagumo',
'browseLabel' => 'Insert Evidence',
'uploadUrl' => Url::to(['cases/upload']),
'maxFileCount' => 10
]
]
);?>
<?php ActiveForm::end(); ?>
案例控制器中的上传操作,由文件输入案例/上传中的URL指定
public function actionUpload(){
//print_r($_FILES['images']);
if (empty($_FILES['name'])) {
echo json_encode(['error'=>'No files found for pload.']);
// or you can throw an exception
return; // terminate
}else{
echo json_encode(['error'=>'files available for upload']);
}
}
上面总是返回错误没有上传文件,表明文件数据没有传递到控制器