yii2.0上傳圖片

來源:互聯網
上載者:User

標籤:控制器   ati   url   tar   sub   exists   self   substr   hint   

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="‘.\app\models\Company::getAvatarUrlById($model->id).‘" width="100px" height="100px" />‘])->staticControl() ?>

結果顯示:
網頁顯示

本地顯示 (當前ID.jpeg)



yii2.0上傳圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.