изображение остается неизменным после обновления и загрузки новых изображений - PullRequest
0 голосов
/ 24 июня 2019

Я загрузил изображение и обрезал его с помощью croppie, изображение успешно обновляет базу данных и успешно входит в каталог.

, но новое изображение перезаписывает старое изображение с тем же именем, это было сделано намеренно.но изображение, отображаемое снова php, остается старым изображением (изображение было перезаписано новым)

Изначально проблем не было, но когда я не открывал проект более 2 недель, былапроблема, подобная описанной выше

HTML-тег

<div class="col-sm-3">
    <h4>Profile Picture</h4>
    <hr>
     <form action="" id="form" method="post">
       <label class="cabinet center-block">
         <figure><img src="" class="gambar img-responsive img-thumbnail" id="item-img-output" />
         <figcaption><i class="fa fa-camera"></i></figcaption>
         </figure>
         <input type="file" class="item-img file center-block" name="file_photo"/>
        </label>
      </form>
</div>

JS с CROPPIE

<script type="text/javascript">
        // Start upload preview image
        $(".gambar").attr("src", "../profile/pictures/img/<?=$profile['profile']?>");
        var $uploadCrop,
        tempFilename,
        rawImg,
        imageId;
        function readFile(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $('.upload-demo').addClass('ready');
                    $('#cropImagePop').modal('show');
                    rawImg = e.target.result;
                }
                reader.readAsDataURL(input.files[0]);
            }
            else {
                swal("Desculpe, seu navegador não suporta o FileReader API.");
            }
        }

        $uploadCrop = $('#upload-demo').croppie({
            viewport: {
                width: 230,
                height: 230,
            },
            enforceBoundary: false,
            enableExif: true
        });
        $('#cropImagePop').on('shown.bs.modal', function(){
            // alert('Shown pop');
            $uploadCrop.croppie('bind', {
                url: rawImg
            }).then(function(){
                console.log('jQuery bind complete');
            });
        });

        $('.item-img').on('change', function () { imageId = $(this).data('id'); tempFilename = $(this).val();
            $('#cancelCropBtn').data('id', imageId); readFile(this); });
        $('#cropImageBtn').on('click', function (ev) {
            $uploadCrop.croppie('result', {
                type: 'base64',
                format: 'jpeg',
                size: {width: 270, height: 270}
            }).then(function (resp) {
                $('#item-img-output').attr('src', resp);
            //$('#cropImagePop').modal('hide');
                $.ajax({
                    url: "../lib/proses/upload.php",
                    type: "POST",
                    data: {"image":resp},
                    success: function (data) {
                        html = '<img src="' + resp + '" />';
                        $("#upload-image-i").html(html);
                        $('#cropImagePop').modal('hide');
                        swal.fire(
                            'Berhasil !',
                            'Profile berhasil diubah',
                            'success'
                        )
                    }
                });
            $('#cropImagePop').modal('hide');
            });
        });
        // End upload preview image  

    </script>

ЗагрузитьПроцесс

<?php 
    session_start();
    require "../koneksi.php";

    $username = $_SESSION['username'];

    $croped_image = $_POST['image'];
    list($type, $croped_image) = explode(';', $croped_image);
    list(, $croped_image)      = explode(',', $croped_image);
    $croped_image = base64_decode($croped_image);
    $image_name = $username.'.png';

    // insert name to database
    $sql = "UPDATE users SET profile = '$image_name' WHERE username = '$username'";
    $query = mysqli_query($conn, $sql);

    // upload cropped image to server 
    file_put_contents('../../profile/pictures/img/'.$image_name, $croped_image);
?>

Я хочу, чтобы вновь загруженное изображение отображалось вместо старого изображения в файле, который отображает изображение (например, индексный файл и т. Д.)

Ответы [ 2 ]

0 голосов
/ 24 июня 2019

Очистить кеш, вы используете PHP-фреймворк?

0 голосов
/ 24 июня 2019

Вы проверили кеш вашего браузера?Возможно, попробуйте добавить случайный параметр в путь к изображению, например, myimage.jpg? C = [randomNumber], это заставит браузер снова загрузить изображение.

...