【问题标题】:Yii2 Update Profile PhotoYii2 更新头像
【发布时间】:2015-05-30 06:11:56
【问题描述】:

我在这里有一个编辑个人资料页面,用户可以在其中更改他/她的个人资料照片/头像。

显示的头像是当前用户的照片(当然),当我点击更新头像按钮时,用户可以选择一个图像,然后选择的图像将预览替换当前用户的头像。

这是我认为的代码:

<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)" 事件放在哪里。

如果您需要更多代码,例如我的动作控制器或模型,请告诉我。

我真的需要这方面的帮助。

【问题讨论】:

    标签: php ajax yii2 avatar


    【解决方案1】:

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

    用户一选择图片,就可以将图片保存在目录和DB表中的文件名中。

    用户选择图片后,使用此小部件2amigon File Upload Widget 开始上传图片。这个小部件呈现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.");
                                      }',
              ],
    ]);
    ?>
    

    Controller :这将调用 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;
    }
    

    除此之外,您可以使用Advanced upload using Yii2 FileInput widget教程了解更多图片上传的详细信息。

    我希望这有助于解决您关于文件上传的问题。

    【讨论】:

    • 我正在尝试使用这个实现,除了用于列出上传文件的返回回调之外,一切似乎都很好。请协助
    • 嗨,返回回调为NULL吗?您是否正确设置了所有变量?
    猜你喜欢
    • 2022-11-22
    • 2016-12-25
    • 2019-05-31
    • 2017-06-07
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多