PHP code example of rplvrtha / yii2-camera

1. Go to this page and download the library: Download rplvrtha/yii2-camera library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rplvrtha / yii2-camera example snippets



use rplvrtha\camera\Yii2Cam;
use yii\helpers\Url;

echo Yii2Cam::widget([
    'uploadUrl' => Url::to(['site/upload-image']),
    'onSuccess' => 'handleSuccess',
    'onError' => 'handleError',
    'buttonText' => 'Ambil Foto',
]);

$this->registerJs(<<<JS
    // Fungsi callback yang dipanggil saat unggah berhasil
    function handleSuccess(response) {
        console.log('Gambar berhasil diunggah:', response);
        alert('Gambar berhasil disimpan di server!');
        // Contoh: menampilkan nama file dari respons server
        if (response.filename) {
            console.log('Nama file:', response.filename);
        }
    }

    // Fungsi callback yang dipanggil saat unggah gagal
    function handleError(error) {
        console.error('Error:', error);
        alert('Terjadi kesalahan saat mengunggah gambar.');
    }
JS);

// dalam SiteController.php

public function actionUploadImage()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    if (Yii::$app->request->isPost) {
        $file = \yii\web\UploadedFile::getInstanceByName('imageFile');
        if ($file) {
            $fileName = 'camera_' . time() . '.' . $file->extension;
            $path = Yii::getAlias('@webroot/media/') . $fileName;

            if ($file->saveAs($path)) {
                return ['success' => true, 'filename' => $fileName];
            }
        }
    }
    return ['success' => false, 'message' => 'Gagal mengunggah file.'];
}