Yii2更新个人资料照片 [英] Yii2 Update Profile Photo

查看:126
本文介绍了Yii2更新个人资料照片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have here an Edit Profile page where user can change his/her profile photo/avatar.

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

The avatar displayed is the photo of the current user (of course) and when I click the Update Avatar button, the user can select an image, and then the selected image will preview replacing the current user avatar.

这是我认为的代码:

<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>

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

The problem is that, whenever I click the Update button at the end of the form, the avatar does not change. I know that this is because it's all in the front end. How do I get the newly selected image and save it to the database? Or are there other implementation aside from this one?

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

BTW, I chose this method because I want to preview the image before and after selection. I tried Kartik's FileInput widget but I don't know where to put the onchange="loadFile(event)" event in the plugin.

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

If you need more code, like my action controller or the model, just let me know.

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

I really need help in this one.

推荐答案

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

I don't know if you have found the solution or not.

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

You can save the picture in directory and filename in DB table as soon as the user selects the picture.

使用此小部件 2amigon文件上传小部件即可尽快开始上传图片用户选择图片.此小部件呈现 jQuery文件上传.

Use this widget 2amigon File Upload Widget to start uploading picture as soon as user selects the picture. This widget renders 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方法.

Controller :This will call UserProfileController/actionUploadProfilePicture method.

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小部件进行高级上传教程,了解图片上传的更多详细信息.

Apart from this, you can use Advanced upload using Yii2 FileInput widget tutorial for more details in picture uploading.

我希望这可以帮助您解决有关文件上传的问题.

I hope this helps and clear your issues regarding file upload.

这篇关于Yii2更新个人资料照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆