我们先来看看在yii2中支持的图片上传怎么进行处理的。
PHP;">
PHP
namespace backend\models;
use Yii;
use yii\web\UploadedFile;
class Upload extends \yii\db\ActiveRecord
{
/**
* @var UploadedFile|Null file attribute
*/
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[["file"],"file",],];
}
}
下面我们看看view层是怎么渲染的
PHP;">
["enctype" => "multipart/form-data"]]); ?>
= $form->field($model,"file")->fileInput() ?>
最后实现controller层的实现
request->isPost) {
$model->file = UploadedFile::getInstance($model,"file");
//文件上传存放的目录
$dir = "../../public/uploads/".date("Ymd");
if (!is_dir($dir))
mkdir($dir);
if ($model->validate()) {
//文件名
$fileName = date("HiiHsHis").$model->file->baseName . "." . $model->file->extension;
$dir = $dir."/". $fileName;
$model->file->saveAs($dir);
$uploadSuccessPath = "/uploads/".date("Ymd")."/".$fileName;
}
}
return $this->render("upload",[
"model" => $model,"uploadSuccessPath" => $uploadSuccessPath,]);
}
}
以上所述是小编给大家介绍的Yii2使用自带的UploadedFile实现的文件上传的相关知识。编程之家 jb51.cc 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持。
原文链接:https://www.f2er.com/php/19518.html