簡體   English   中英

Yii2更新個人資料照片

[英]Yii2 Update Profile Photo

我在這里有一個“編輯個人資料”頁面,用戶可以在其中更改他/她的個人資料照片/頭像。

在此處輸入圖片說明

顯示的頭像是當前用戶的照片(當然),當我單擊“更新頭像”按鈕時,用戶可以選擇圖像,然后所選圖像將預覽以替換當前用戶的頭像。

在此處輸入圖片說明

這是我認為的代碼:

<div class="fileUpload btn btn-warning">
    <span>Update Avatar</span>
    <input type="file" accept="image/*" onchange="loadFile(event)" class="upload"/>
</div>
<script>
    var loadFile = function(event) {
    var output = document.getElementById('output');
    output.src = URL.createObjectURL(event.target.files[0]);
  };
</script>

問題是,每當我單擊表單末尾的“更新”按鈕時,頭像都不會更改。 我知道這是因為一切都在前端。 如何獲取新選擇的圖像並將其保存到數據庫? 還是除此以外還有其他實現?

順便說一句,我選擇這種方法是因為我想在選擇之前和之后預覽圖像。 我嘗試了Kartik的FileInput小部件,但不知道在插件中放置onchange="loadFile(event)"事件的位置。

如果您需要更多代碼,例如我的動作控制器或模型,請告訴我。

我真的需要這方面的幫助。

我不知道您是否找到了解決方案。

用戶選擇圖片后,可以立即將圖片保存在目錄中,並將其保存在數據庫表的文件名中。

用戶選擇圖片后,使用此小工具2amigon文件上傳小工具即可開始上傳圖片。 這個小部件呈現jQuery File Upload

用法

視圖

use dosamigos\fileupload\FileUploadUI;

<?= FileUploadUI::widget([
        'model' => $model,
        'attribute' => 'profile_pic',
        'url' => ['user-profile/upload-profile-picture', 'id' => $model->id],
         'gallery' => false,
         'fieldOptions' => [
             'accept' => 'image/*',
         ],
         'clientOptions' => [  
             'maxFileSize' => 2000000,
             'autoUpload' => true,
          ],
          'clientEvents' => [
              'fileuploaddone' => 'function(e, data) {
                                      jQuery(".fb-image-profile").attr("src",data.result);
                                  }',
              'fileuploadfail' => 'function(e, data) {
                                      alert("Image Upload Failed, please try again.");
                                  }',
          ],
]);
?>

控制器 :這將調用UserProfileController / actionUploadProfilePicture方法。

public function actionUploadProfilePicture($id)
{
    $model = $this->findModel($id);
    $oldFile = $model->getProfilePictureFile();
    $oldProfilePic = $model->profile_pic;

    if ($model->load(Yii::$app->request->post())) {

        // process uploaded image file instance
        $image = $model->uploadProfilePicture();

        if($image === false && !empty($oldProfilePic)) {
            $model->profile_pic = $oldProfilePic;
        }

        if ($model->save()) {
            // upload only if valid uploaded file instance found
            if ($image !== false) { // delete old and overwrite
                if(!empty($oldFile) && file_exists($oldFile)) {
                    unlink($oldFile);
                }
                $path = $model->getProfilePictureFile();
                $image->saveAs($path);
            }
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            return $model->getProfilePictureUrl();
        }
    }
}

模型

public function getProfilePictureFile()
{
    return isset($this->profile_pic) ? Yii::$app->params['uploadPath'] . 'user/profile/' . $this->profile_pic : null;
}

public function getProfilePictureUrl()
{
    // return a default image placeholder if your source profile_pic is not found
    $profile_pic = isset($this->profile_pic) ? $this->profile_pic : 'default_user.jpg';
    return Yii::$app->params['uploadUrl'] . 'user/profile/' . $profile_pic;
}

/**
* Process upload of profile picture
*
* @return mixed the uploaded profile picture instance
*/
public function uploadProfilePicture() {
    // get the uploaded file instance. for multiple file uploads
    // the following data will return an array (you may need to use
    // getInstances method)
    $image = UploadedFile::getInstance($this, 'profile_pic');

    // if no image was uploaded abort the upload
    if (empty($image)) {
        return false;
    }

    // store the source file name
    //$this->filename = $image->name;
    $ext = end((explode(".", $image->name)));

    // generate a unique file name
    $this->profile_pic = Yii::$app->security->generateRandomString().".{$ext}";

    // the uploaded profile picture instance
    return $image;
}

除此之外,您還可以使用使用Yii2 FileInput小部件教程進行高級上傳,以獲取圖片上傳的更多詳細信息。

希望這對您有所幫助,並解決了有關文件上傳的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM