view视图create.php
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
<?php $form = ActiveForm::begin([
‘id‘ => ‘upload‘,
‘enableAjaxValidation‘ => false,
‘options‘ => [‘enctype‘ => ‘multipart/form-data‘]
]);
?>
<?= $form->field($model, ‘thumbnail_url‘)->fileInput(); ?>
<?= Html::submitButton($model->isNewRecord ? ‘Create‘ : ‘Update‘, [‘class‘ => $model->isNewRecord ? ‘btn btn-success‘ : ‘btn btn-primary‘]) ?>
<?php ActiveForm::end(); ?>
控制器方法
public function actionCreate()
{
$model = new 数据表model();
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model,‘数据表存储字段‘);
$ext = $image->getExtension();
$imageName = time().rand(100,999).‘.‘.$ext;
$image->saveAs(‘uploads/‘.$imageName);//设置图片的存储位置
$model->数据表存储字段 = ‘http://www.xxx.cn/uploads/‘.$imageName;//设置图片的url,可以用_SERVER["HTTP_HOST"]+图片名代替
$model->save();
$this->render(‘create‘, [
‘model‘ => $model,
]);
}
官方权威指南:文件上传,http://www.yiichina.com/doc/guide/2.0/input-file-upload
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-08 23:45:38