yii2.0文件上传到本地 [ 技术分享 ]
view试图
<?php
$form = ActiveForm::begin([
'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data','class' => 'form-horizontal',]
]) ?>
<?= $form->field($model, 'file[]')->fileInput(['multiple' => true])->label("") ?>
<?php ActiveForm::end() ?>
model模型
<?php
namespace backend\models;
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* @var UploadedFile[]
*/
public $file;
public function rules()
{
return [
[['file'], 'file', 'extensions' => 'jpg, png', 'mimeTypes' => 'image/jpeg, image/png', 'maxFiles' => 10],
];
}
// public function attributeLabels(){
// return [
// 'file' => '商品缩略图上传',
// ];
// }
}
控制器Controller
public function actionInsert(){
$model = new UploadForm();
if (Yii::$app->request->isPost) {
$files = UploadedFile::getInstances($model, 'file');
foreach ($files as $file) {
$_model = new UploadForm();
$_model->file = $file;
if ($_model->file) {
if(!file_exists('uploads/')){
mkdir('uploads/',0777,true);
}
$_model->file->saveAs('uploads/' . $_model->file->baseName . '.' . $_model->file->extension);
} else {
foreach ($_model->getErrors('file') as $error) {
$model->addError('file', $error);
}
}
}
}
return $this->render('insert', ['model' => $model]);
}
共 0 条回复
没有找到数据。
fcq 上海
注册时间:2015-11-25
最后登录:2018-09-10
在线时长:7小时51分
最后登录:2018-09-10
在线时长:7小时51分
- 粉丝0
- 金钱15
- 威望0
- 积分85