首页 > 代码库 > yii2.0上传图片

yii2.0上传图片

model:

use Yii;
/**
* 获取头像url地址
* @return 头像的url地址
*/
public function getPortraitUrl()
{
return self::getAvatarUrlById($this->id);
}

/**
* 获取头像存放路径
* @return 头像的存放路径
*/
public static function getAvatarPathById($companyId)
{
$string = str_pad($companyId, 6, ‘0‘, STR_PAD_LEFT);
$path = ‘company/‘ . substr($string, 0, -4) . ‘/‘ . substr($string, -4, 2) . ‘/‘ . substr($string, -2, 2) . image_type_to_extension(IMAGETYPE_JPEG);;
return $path;
}

/**
* 通过用户ID获取头像url地址
*/
public static function getAvatarUrlById($companyId)
{
$path = self::getAvatarPathById($companyId);
$file = Yii::getAlias(‘@uploadPath/‘ . $path);
if (file_exists($file)) {
$makeTime = filemtime($file);
return Yii::getAlias(‘@uploadUrl/‘ . $path) . ‘?‘ . $makeTime;
}
return Yii::getAlias(‘@resUrl/‘ . self::DEFAULT_AVATAR);
}
控制器:
use Yii;
use app\models\Company;
use yii\helpers\FileHelper;
use yii\web\Controller;
use yii\web\UploadedFile;
public function actionProfile()
{
$id = Yii::$app->session[‘companyId‘];//得到id
$model = Company::findOne($id);
$imageUpload = UploadedFile::getInstance($model, ‘imageUpload‘);//返回一个上传文件
if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {//判断是否post提交,加载数据
if ($imageUpload && $model->validate([‘imageUpload‘])) {//数据验证
$path = Company::getAvatarPathById($id);//图片的路径别名
$avatarImage = Yii::getAlias(‘@uploadPath/‘ . $path);//将路径别名转化为实际的路径
FileHelper::createDirectory(dirname(Yii::getAlias($avatarImage)));//创建目录
$imageUpload->saveAs(Yii::getAlias($avatarImage));//保存图片
}
if($model->save()) {
Yii::$app->session[‘companyName‘] = $model->name;
}
}
return$this->render(‘profile‘, [‘model‘ => $model]);
}
视图显示:
use app\models\Company;
<?= $form->field($model, ‘imageUpload‘)->fileInput([‘maxlength‘ => true])->hint(‘建议上传尺寸:100*100--300*300‘) ?>

<?= $form->field($model, ‘imageUpload‘, [‘inputTemplate‘=>‘<img src="http://www.mamicode.com/‘./app/models/Company::getAvatarUrlById($model->id).‘" width="100px" height="100px" />‘])->staticControl() ?>

结果显示:
网页显示
技术分享
本地显示 (当前ID.jpeg)

技术分享


yii2.0上传图片