例子:
1.在表单中:
<?php $form = \yii\widgets\ActiveForm::begin([ 'options'=>[ 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data' ], 'fieldConfig' => [ 'template' => '{input}{error}', 'options' => ['class' => 'form-field'], ], ]); ?>
注意:上传图片必须修改表单提交必须是以二进制数据流的形式;必须配置
'enctype' => 'multipart/form-data'
<?= $form->field($model, 'wms_check_certificate')->label("差异清单截图")->widget(\kartik\widgets\FileInput::className(), [ 'options' => [ 'accept' => 'image/jpg, image/jpeg, image/png, image/gif', 'multiple' => false, ], 'pluginOptions' => [ 'previewFileType' => 'image', 'initialPreview' => !empty($model->wms_check_certificate) ? $model->wms_check_certificate : "", 'initialPreviewConfig'=>[], 'overwriteInitial'=>true, 'initialPreviewAsData' => true, 'uploadUrl' => \yii\helpers\Url::toRoute(['upload']), 'uploadExtraData' => ['id'=>$model->id], 'allowedFileExtensions' => ['jpg', 'png','gif', 'jpeg'], 'uploadAsync' => true, 'minFileCount' => 0, 'maxFileCount' => 1, 'showRemove' => true, 'showUpload' => true, 'showBrowse' => true, 'showPreview' => true, 'showCaption' => false, 'browseOnZoneClick' => true, 'fileActionSettings' => [ 'showZoom' => true, 'showUpload' => true, 'showRemove' => true, ], ], 'pluginEvents' => [ "fileclear" => "function() { $('#wmscheck-wms_check_certificate').val(''); }", "fileuploaded" => "function (event, data, id, index) { console.log(data); }", ], ]) ?>
注意:
'accept' => 'image/jpg, image/jpeg, image/png, image/gif', 指的是上传的文件的格式必须是jpg,png和gif
'multiple' => false,指的是不支持上传多个文件
'previewFileType' => 'image',指的是上传的文件必须是图片
'initialPreview' => !empty($model->wms_check_certificate) ? $model->wms_check_certificate : "",指的是刚进入页面时默认显示的文件
'uploadUrl' => \yii\helpers\Url::toRoute(['upload']),指的是上传文件的ur地址
'uploadExtraData' => ['id'=>$model->id],指的是上传文件时附带的数据
'allowedFileExtensions' => ['jpg', 'png','gif', 'jpeg'],指的是支持的文件后缀
'uploadAsync' => true,指的是是否以异步形式上传
'showUpload' => true,是否显示上传按钮
'showBrowse' => true,是否显示打开文件对话框按钮
'showRemove' => true,是否显示移除按钮
'showCaption' => false,是否显示方法查看按钮
2.在后台处理上传:
public function actionUpload(){ $id = $_REQUEST['id']; if(!empty($_FILES['WmsCheck']['tmp_name']['wms_check_certificate'])){ $wms_check_certificate = \common\models\Base::uploadCloud($_FILES['WmsCheck']['tmp_name']['wms_check_certificate'], $_FILES['WmsCheck']['name']['wms_check_certificate'], 'wms'); $model = \core\models\WmsCheck::findOne(['id'=>$id]); if (empty($model)){ echo json_encode(['msg'=>false]); }else{ $model->wms_check_certificate = $wms_check_certificate; $save_handler = $model->save(false); echo json_encode(['msg'=>$save_handler]); } }else{ echo json_encode(['msg'=>false]); } }