Yii2更新个人资料照片

时间:2015-03-26 09:25:39

标签: php ajax yii2 avatar

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

enter image description here

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

enter image description here

这是我视图中的代码:

<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)"事件放在插件中的哪个位置。

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

我真的需要帮助。

1 个答案:

答案 0 :(得分:5)

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

用户选择图片后,您可以将图片保存在数据库表格中的目录和文件名中。

使用此小部件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.");
                                  }',
          ],
]);
?>

控制器:这将调用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教程了解图片上传的详细信息。

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