Upload image and set avatar

Hi I want to set custom avatar image. for this user upload their photo. how to achieve this with cocos creator, how to prompt file upload box and update sprite?
@RAAng @huynhthuan @linrm @zzf_Cocos @slackmoehrle @nutrino

1 Like

resolved.

1 Like

hello there,

could you share how did you solve it?

1 Like

Hello,
It would be great If the solution was posted.

I got the solution not sure if this is the efficient way.

    @property(cc.Sprite)
    targetSprite: cc.Sprite = null;

    inputElement: HTMLInputElement;

    onLoad() {
        this.inputElement = document.createElement('input');
        this.inputElement.type = 'file';
        this.inputElement.accept = 'image/png, image/jpeg, image/jpg, image/gif';
        this.inputElement.name = 'myFile';
        this.inputElement.id = 'imageInput';

        this.inputElement.addEventListener('change', this.handleImageUpload.bind(this));
    }

    onUploadFile() {  //This is called on button click
        this.inputElement.click();
    }

    handleImageUpload(event: Event) {
        const inputElement = event.target as HTMLInputElement;
        if (inputElement.files && inputElement.files.length > 0) {
            const selectedFile = inputElement.files[0];
            const reader = new FileReader();
            reader.onload = (e: ProgressEvent<FileReader>) => {
                const texture = new cc.Texture2D();
                const image = new Image();
                image.src = e.target.result as string;
                texture.initWithElement(image);

                const spriteFrame = new cc.SpriteFrame(texture);
                // Assign the sprite frame to your target sprite component
                this.targetSprite.spriteFrame = spriteFrame;
            };
            reader.readAsDataURL(selectedFile);
        }
    }
}