Yii2更新个人资料照片

kay*_*der 0 php ajax avatar yii2

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

在此输入图像描述

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

在此输入图像描述

这是我视图中的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

问题是,每当我单击表单末尾的"更新"按钮时,头像都不会改变.我知道这是因为它都在前端.如何获取新选择的图像并将其保存到数据库?或者除此之外还有其他实现吗?

顺便说一下,我之所以选择这种方法,是因为我想在选择之前和之后预览图像.我尝试了Kartik的FileInput小部件,但我不知道将该onchange="loadFile(event)"事件放在插件中的哪个位置.

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

我真的需要帮助.

Moh*_*ali 5

我不知道你是否找到了解决方案.

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

使用此小部件2amigon文件上载小工具可在用户选择图片后立即开始上传图片.此小部件呈现jQuery文件上载.

用法:

视图

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.");
                                  }',
          ],
]);
?>
Run Code Online (Sandbox Code Playgroud)

控制器:这将调用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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

模型

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;
}
Run Code Online (Sandbox Code Playgroud)

除此之外,您还可以使用Yii2 FileInput小部件教程使用高级上传,以获取图片上传的更多详细信息.

我希望这有助于清除有关文件上传的问题.