azzt test

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » azzt test » Тестовый форум » тест


тест

Сообщений 1 страница 2 из 2

1

тесттест

0

2

первая рабочая версия

Код:
<script>
(function() {
    const IMGBB_API_KEY = '04884a3dd472a5d22ec1beb90b57503b';
    const IMGBB_UPLOAD_URL = 'https://api.imgbb.com/1/upload';
    const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
    const MAX_DIMENSION = 1500;
    
    $(document).ready(function() {
        setTimeout(function() {
            patchImageUpload();
        }, 1000);
    });
    
    function patchImageUpload() {
        var $uploadInput = $("#image_upload_input");
        
        if ($uploadInput.length === 0) {
            console.log("Upload input не найден");
            return;
        }
        
        console.log("Патчим загрузку изображений...");
        
        // ПОЛНОСТЬЮ отключаем оригинальный обработчик fileuploadadd
        $uploadInput.off('fileuploadadd');
        
        // Добавляем свой обработчик
        $uploadInput.on('fileuploadadd', function(e, data) {
            console.log("Файл добавлен через наш обработчик");
            handleCustomFileAdd(e, data);
        });
        
        // Также перехватываем остальные события для совместимости
        $uploadInput.off('fileuploadstart fileuploadprogress fileuploaddone fileuploadfail');
        
        $uploadInput.on('fileuploadstart', function() {
            $("#upload-button-container").hide();
        });
    }
    
    function handleCustomFileAdd(e, data) {
        console.log("Обрабатываем файлы:", data.files.length);
        
        $.each(data.files, function(index, file) {
            if (!file.name.match(/(\.|\/)(gif|jpe?g|png|webp)$/i)) {
                alert("Недопустимый тип файла " + file.name + ".");
                return false;
            }
            
            var uploadID = "f" + Math.random().toString().substr(6);
            var fileSize = (file.size / 1000).toFixed(2) + " kB";
            var fileName = file.name.length <= 34 ? file.name : file.name.substr(0, 32) + "...";
            
            file.uploadID = uploadID;
            
            // Проверяем, нет ли уже такого файла в очереди
            if ($('.uploadQueueItem[data-modified="' + file.lastModified + '"][data-name="' + file.name + '"]').length > 0) {
                console.log("Файл уже в очереди");
                return;
            }
            
            var queueItem = $(`
                <div class="uploadQueueItem" id="upload_${uploadID}" data-name="${file.name}" data-modified="${file.lastModified}">
                    <div class="cancel"><a href="javascript://">×</a></div>
                    <span class="fileName">${fileName} (${fileSize})</span>
                    <span class="percentage"></span>
                    <div class="uploadProgress">
                        <div class="uploadProgressBar"><!-- --></div>
                    </div>
                    <button type="button" class="btn btn-primary fileupload" id="btn-${uploadID}">Загрузить</button>
                </div>
            `);
            
            // Обработчик кнопки загрузки - только один preventDefault
            queueItem.find('.btn').on('click', function(e) {
                e.preventDefault(); // только это, чтобы не отправлять форму
                
                console.log("Нажата кнопка загрузки для файла:", file.name);
                
                var $btn = $(this);
                $btn.addClass('startedUpload').off('click');
                
                processAndUploadToImgbb(file);
            });
            
            // Обработчик отмены
            queueItem.find('.cancel').on('click', function(e) {
                e.preventDefault();
                queueItem.remove();
                checkQueueVisibility();
            });
            
            $("#imageQueue").append(queueItem);
        });
        
        // Показываем интерфейс
        showUploadInterface();
    }
    
    async function processAndUploadToImgbb(file) {
        var uploadID = file.uploadID;
        var $uploadItem = $("#upload_" + uploadID);
        
        console.log("Функция processAndUploadToImgbb вызвана для:", file.name);
        
        try {
            // Сжимаем если нужно
            var processedFile = file;
            if (file.size > MAX_FILE_SIZE) {
                $uploadItem.find('.percentage').text(' - сжатие...');
                processedFile = await compressImage(file);
                console.log("Файл сжат с", file.size, "до", processedFile.size);
            }
            
            // Конвертируем в base64
            $uploadItem.find('.percentage').text(' - подготовка...');
            var base64Data = await fileToBase64(processedFile);
            var base64Image = base64Data.split(',')[1];
            
            console.log("Файл конвертирован в base64, размер:", base64Image.length);
            
            // Загружаем на imgbb
            $uploadItem.find('.percentage').text(' - загрузка...');
            
            var formData = new FormData();
            formData.append('key', IMGBB_API_KEY);
            formData.append('image', base64Image);
            
            console.log("Отправляем запрос на imgbb...");
            
            $.ajax({
                url: IMGBB_UPLOAD_URL,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                xhr: function() {
                    var xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', function(evt) {
                        if (evt.lengthComputable) {
                            var percentComplete = parseInt(evt.loaded / evt.total * 100, 10);
                            $uploadItem.find('.uploadProgressBar').css('width', percentComplete + '%');
                            $uploadItem.find('.percentage').text(' - ' + percentComplete + '%');
                        }
                    }, false);
                    return xhr;
                },
                success: function(response) {
                    console.log("Ответ imgbb:", response);
                    handleImgbbSuccess(response, uploadID);
                },
                error: function(xhr, status, error) {
                    console.error("Ошибка загрузки:", error);
                    handleUploadError(uploadID, error);
                }
            });
            
        } catch (error) {
            console.error("Ошибка обработки:", error);
            handleUploadError(uploadID, error.message);
        }
    }
    
    function compressImage(file) {
        return new Promise((resolve, reject) => {
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            var img = new Image();
            
            img.onload = function() {
                var { width, height } = calculateNewDimensions(img.width, img.height, MAX_DIMENSION);
                
                canvas.width = width;
                canvas.height = height;
                ctx.drawImage(img, 0, 0, width, height);
                
                canvas.toBlob(function(blob) {
                    if (blob) {
                        var compressedFile = new File([blob], file.name, {
                            type: blob.type,
                            lastModified: Date.now()
                        });
                        compressedFile.uploadID = file.uploadID;
                        resolve(compressedFile);
                    } else {
                        reject(new Error('Не удалось сжать изображение'));
                    }
                }, file.type, 0.8);
            };
            
            img.onerror = function() {
                reject(new Error('Не удалось загрузить изображение'));
            };
            
            img.src = URL.createObjectURL(file);
        });
    }
    
    function calculateNewDimensions(originalWidth, originalHeight, maxDimension) {
        var width = originalWidth;
        var height = originalHeight;
        
        if (width > height) {
            if (width > maxDimension) {
                height = (height * maxDimension) / width;
                width = maxDimension;
            }
        } else {
            if (height > maxDimension) {
                width = (width * maxDimension) / height;
                height = maxDimension;
            }
        }
        
        return { width: Math.round(width), height: Math.round(height) };
    }
    
    function fileToBase64(file) {
        return new Promise((resolve, reject) => {
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }
    
    function handleImgbbSuccess(response, uploadID) {
        var $uploadItem = $("#upload_" + uploadID);
        
        if (response.success) {
            var imageData = response.data;
            var thumbnailUrl = imageData.thumb ? imageData.thumb.url : imageData.url;
            var originalUrl = imageData.url;
            
            console.log("Создаем элемент изображения:", imageData.id);
            
            // Создаем элемент точно как в оригинале
            var imageHtml = `<img id="${imageData.id}" src="${thumbnailUrl}" title="Вставить" data-img-url="${originalUrl}" data-img-view="${originalUrl}" onClick="insertUploadedImage(this);changeVisibility('image-area');" />`;
            
            // Если нет изображений, то устанавливаем высоту очереди
            if ($("#uploaded-images img").length === 0) {
                $("#imageQueue").css("max-height", 66);
            }
            
            $("#uploaded-images").append(imageHtml);
            $uploadItem.remove();
            
            // Показываем панель с изображениями
            $("#uploaded-images,#image-insert-format,#insert-all-images-container,#insert-image-tip,#action-insert-uploaded,#action-clean-uploaded,#action-drop-files").show();
            
            // Инициализируем tipsy если функция доступна
            if (typeof $.fn.tipsy !== 'undefined') {
                $("#" + imageData.id.replace(".", "\\.")).tipsy({
                    gravity: "s"
                });
            }
            
            checkQueueVisibility();
            initInsertFormat();
            
        } else {
            handleUploadError(uploadID, response.error ? response.error.message : 'Неизвестная ошибка');
        }
    }
    
function initInsertFormat() {
    if ($("#image-insert-format").is(":empty") && typeof FORUM !== 'undefined') {
        var formatOptions = "";
        var imgBbcodes = FORUM.get("editor.image.img_bbcodes");
        if (imgBbcodes) {
            $.each(imgBbcodes, function(key, format) {
                // Принудительно устанавливаем source как выбранный по умолчанию
                var isSelected = (key === 'source');
                formatOptions += '<option value="' + key + '"' + (isSelected ? ' selected="selected"' : '') + '>' + format.name + '</option>';
            });
            $("#image-insert-format").append('<strong>Вставить как:</strong><br /><select id="selected-insert-format">' + formatOptions + '</select>');
        }
    }
}    
    function handleUploadError(uploadID, errorMessage) {
        $("#upload_" + uploadID).removeClass('process').addClass('error')
            .find('.percentage').text(' - ' + errorMessage);
    }
    
    function showUploadInterface() {
        $("#imageQueue").show();
        $("#load-image-container,#upload-button-container,#action-clean-uploaded").show();
        
        if ($("#uploaded-images img").length === 0) {
            $("#imageQueue").css("max-height", 150);
        }
        
        initInsertFormat();
    }
    
    function checkQueueVisibility() {
        if ($("#imageQueue div.uploadQueueItem").length === 0) {
            $("#imageQueue").hide();
            $("#upload-button-container").hide();
        }
        
        if ($("#uploaded-images img").length === 0 && $("#imageQueue div.uploadQueueItem").length === 0) {
            $("#action-clean-uploaded").hide();
            $("#load-image-container").hide();
        }
    }
    
    console.log("Скрипт imgbb загружен");
    
})();
</script>

<style>
.uploadQueueItem .btn { display: none; }
</style>

0


Вы здесь » azzt test » Тестовый форум » тест


Рейтинг форумов | Создать форум бесплатно