티스토리 뷰

반응형

 // 파일 업로드 처리 함수가 있다. 이를 이용해서 chatGPT로 원하는 결과를 도출하는 과정을 함께 담아본다.

1. 쳇GPT에서 기존 코드로 질문하기


function uploadFiles(files) {
        isUploading = true;  // 업로드 중 상태 설정
        showUploadModal();  // 업로드 중 모달 표시

        var formData = new FormData($('#board_form')[0]);

// 현재 폼 데이터에 추가된 파일 이름 목록 추적
var existingFiles = new Set();
for (var pair of formData.entries()) {
if (pair[0] === 'upfile[]') {
existingFiles.add(pair[1].name);
}
}

// 중복되지 않은 파일만 추가
for (var i = 0; i < files.length; i++) {
if (!existingFiles.has(files[i].name)) {
formData.append('upfile[]', files[i]);
existingFiles.add(files[i].name);  // 추가된 파일 이름을 목록에 저장
console.log('파일 추가:', files[i].name);  // 디버그
} else {
console.log('중복 파일 무시:', files[i].name);  // 디버그
}
}
        if (ajaxRequest5 !== null) {
            ajaxRequest5.abort();
        }

        ajaxRequest5 = $.ajax({
            enctype: 'multipart/form-data',
            processData: false,
            contentType: false,
            cache: false,
            timeout: 700000,
            url: "/file/file_insert.php",
            type: "POST",
            data: formData,
            success: function(data_insertfile) {
                console.log(data_insertfile);
                loadFiles();  // 파일 목록 재로드
                hideUploadModal();  // 업로드 완료 모달 숨기기
                isUploading = false;  // 업로드 중 상태 해제
            },
            error: function(jqxhr, status, error) {
                console.log("업로드 실패: ", jqxhr, status, error);
                hideUploadModal();  // 업로드 실패 모달 숨기기
                isUploading = false;  // 업로드 중 상태 해제
            }
        });
    }
  
function loadFiles() {
    var params = $("#num").val();
    var url = '/file/load_file.php?id=' + params + '&tablename=workdb&item=image';

    if (ajaxRequest7 !== null) {
        ajaxRequest7.abort();
    }

    ajaxRequest7 = $.ajax({
        url: url,
        type: "POST",
        data: $("#board_form").serialize(),
        dataType: "json",
        success: function(data_attached_exist) {
            ajaxRequest7 = null;
            isDisplaying = false;

            var fileListDiv = $('<div>').css({
                display: 'flex',
                flexWrap: 'wrap',
                justifyContent: 'flex-start', // 이미지를 왼쪽부터 정렬
                gap: '10px', // 이미지 간의 간격
                maxHeight: '3000px',
                maxWidth: '1300px',
                marginBottom: '5px'
            });

            for (var i = 0; i < data_attached_exist["recid"]; i++) {
                var fileDiv = $('<div>').attr('id', 'file' + i).css({
                    flex: '1 1 calc(8% - 10px)', // 기본적으로 20%의 너비를 차지하며, 여유 공간을 잘 채우도록 설정
                    textAlign: 'center',
                    marginBottom: '10px',
                    position: 'relative'
                });

                // 이미지 태그 생성
                var img = $('<img>').attr('src', '/uploads/' + data_attached_exist["file_arr"][i])
                                    .attr('alt', data_attached_exist["realfile_arr"][i])
                                    .addClass('thumbnail-img')  // CSS 클래스 추가
                                    .css({
                                        maxWidth: '50px',
                                        maxHeight: '50px',
                                        display: 'block',
                                        marginBottom: '5px',
                                        cursor: 'pointer' // 커서를 포인터로 변경
                                    });

                var fileDeleteBtn = $('<span>').attr({
                    type: 'button',
                    class: 'text-danger',
                    id: 'delPic' + i,
                    onclick: "delPicFn('" + i + "','" + data_attached_exist["file_arr"][i] + "')"
                }).html('<i class="bi bi-x-circle"></i>');

                fileDiv.append(img).append(fileDeleteBtn);
                fileListDiv.append(fileDiv);

                // 이미지 클릭 이벤트 핸들러
                img.on('click', function() {
                    var overlay = $('<div>').attr('id', 'image-overlay').css({
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        width: '100%',
                        height: '100%',
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        zIndex: 10000,
                        cursor: 'pointer'
                    }).appendTo('body');

                    var enlargedImg = $('<img>').attr('src', $(this).attr('src')).css({
                        maxWidth: '90%',
                        maxHeight: '90%'
                    }).appendTo(overlay);

                    // 클릭 시 이미지 확대 창 닫기
                    overlay.on('click', function() {
                        $(this).remove();
                    });
                });
            }

            $('#displayfile').html(fileListDiv);
        },
        error: function(jqxhr, status, error) {
            console.log(jqxhr, status, error);
        }
    });
}
    
// 파일 삭제 함수
    window.delPicFn = function(i, fileName) {
        Swal.fire({
            title: '첨부파일 삭제',
            text: "삭제는 신중해야 합니다. 삭제 하시겠습니까?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: '삭제',
            cancelButtonText: '취소'
        }).then((result) => {
            if (result.isConfirmed) {
                if (ajaxRequest6 !== null) {
                    ajaxRequest6.abort();
                }

                ajaxRequest6 = $.ajax({
                    url: '/file/del_file.php?savename=' + fileName,
                    type: 'post',
                    data: $("#board_form").serialize(),
                    dataType: 'json',
                    success: function(data) {
                        ajaxRequest6 = null;
                        $("#file" + i).remove(); // 파일 삭제
                        $("#delPic" + i).remove(); // 버튼 삭제
                    },
                    error: function(jqxhr, status, error) {
                        ajaxRequest6 = null;
                        console.log(jqxhr, status, error);
                    }
                });
            }
        });
    } // end of delPicFn

  // 업로드 중 모달 표시 함수
    function showUploadModal() {
        var modal = $('<div>').attr('id', 'uploadModal').css({
            position: 'fixed',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            backgroundColor: '#fff',
            padding: '20px',
            borderRadius: '10px',
            boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)',
            zIndex: 10000,
            textAlign: 'center'
        }).text('사진을 올리고 있습니다. 잠시만 기다려 주세요.');

        var overlay = $('<div>').attr('id', 'overlay').css({
            position: 'fixed',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            backgroundColor: 'rgba(0, 0, 0, 0.5)',
            zIndex: 9999
        });

        $('body').append(overlay).append(modal);
    }

    // 업로드 완료 모달 숨기기 함수
    function hideUploadModal() {
        $('#uploadModal').remove();
        $('#overlay').remove();
    }
});

</script>

</body>

위의 코드에서 업로드, 저장 등의 버튼을 누르면 화면을 어둡게 해서 그 결과값 즉 처리가 끝나면 화면이 다시 정상으로 돌아오는 코드가 있다.

이 코드를 함수화해서 어디서든 같은 식으로 호출하고 다시 정상으로 돌리고 하는 동작을 하려고 한다.

단, 전달하는 함수에는 문구 즉' 이미지를 업로드 중입니다.' '파일을 업로드 중입니다.' 이를 선택 옵션으로 처리하고 싶다. 1이면 이미지, 2이면 파일업로드 
마지막에 '잠시만 기다려 주세요!'라는 문구까지 넣어서 말이다.

호출하면 동작하는 함수와 닫는 함수가 있어야겠지?

이 코드로 만들수 있겠지?
ChatGPT의 말:
ChatGPT
아래와 같이 함수화를 진행하여 원하는 작업을 구현할 수 있습니다. 호출할 때 문구를 선택적으로 전달하여 업로드 작업의 유형을 나타내고, 닫는 함수를 별도로 정의하여 재사용할 수 있도록 구성했습니다.

구현 코드
// 업로드 상태를 표시하는 함수
function showUploadModal(type) {
    var message = '';
    switch (type) {
        case 1:
            message = '이미지를 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 2:
            message = '파일을 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        default:
            message = '처리 중입니다. 잠시만 기다려 주세요!';
    }

    var modal = $('<div>').attr('id', 'uploadModal').css({
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: '#fff',
        padding: '20px',
        borderRadius: '10px',
        boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)',
        zIndex: 10000,
        textAlign: 'center'
    }).text(message);

    var overlay = $('<div>').attr('id', 'overlay').css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 9999
    });

    $('body').append(overlay).append(modal);
}

// 업로드 완료 후 모달을 숨기는 함수
function hideUploadModal() {
    $('#uploadModal').remove();
    $('#overlay').remove();
}

// 호출 예시
// 이미지를 업로드 중일 때
showUploadModal(1);
// 파일을 업로드 중일 때
showUploadModal(2);

// 작업 완료 후 모달 닫기
hideUploadModal();
사용법
showUploadModal(type)
type에 따라 문구를 설정합니다.
1: "이미지를 업로드 중입니다. 잠시만 기다려 주세요!"
2: "파일을 업로드 중입니다. 잠시만 기다려 주세요!"
기타: "처리 중입니다. 잠시만 기다려 주세요!"
hideUploadModal()
모달과 오버레이를 제거하여 화면을 정상적으로 되돌립니다.
통합된 코드 예시
function performUploadExample() {
    // 1. 업로드 모달 표시
    showUploadModal(1);

    // 2. 업로드 작업 진행
    setTimeout(() => {
        console.log("업로드 완료");
        
        // 3. 업로드 완료 후 모달 숨기기
        hideUploadModal();
    }, 3000); // 업로드 작업을 3초간 시뮬레이션
}

// 함수 호출 예제
performUploadExample();
이 구조로 호출하면 문구를 설정하고, 작업 완료 후 화면을 정상으로 돌리는 기능을 재사용할 수 있습니다.






나의 말:
showUploadModal 이라기 보다는 showMsgModal 이란 이름이 더 좋겠다. 여러가지로 활용할 거니까.
ChatGPT의 말:
ChatGPT
아래는 showMsgModal이라는 이름으로 변경한 코드입니다. 이 코드는 메시지를 설정할 수 있고, 다양한 상황에서 재사용할 수 있습니다.

구현 코드
// 메시지 모달 표시 함수
function showMsgModal(type) {
    var message = '';
    switch (type) {
        case 1:
            message = '이미지를 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 2:
            message = '파일을 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 3:
            message = '데이터를 처리 중입니다. 잠시만 기다려 주세요!';
            break;
        default:
            message = '작업을 처리 중입니다. 잠시만 기다려 주세요!';
    }

    var modal = $('<div>').attr('id', 'msgModal').css({
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: '#fff',
        padding: '20px',
        borderRadius: '10px',
        boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)',
        zIndex: 10000,
        textAlign: 'center'
    }).text(message);

    var overlay = $('<div>').attr('id', 'msgOverlay').css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 9999
    });

    $('body').append(overlay).append(modal);
}

// 메시지 모달 숨기기 함수
function hideMsgModal() {
    $('#msgModal').remove();
    $('#msgOverlay').remove();
}

// 호출 예시
// 이미지를 업로드 중일 때
showMsgModal(1);
// 파일을 업로드 중일 때
showMsgModal(2);
// 작업 완료 후 모달 닫기
hideMsgModal();
사용법
showMsgModal(type)
type 매개변수에 따라 메시지를 설정합니다.
1: "이미지를 업로드 중입니다. 잠시만 기다려 주세요!"
2: "파일을 업로드 중입니다. 잠시만 기다려 주세요!"
3: "데이터를 처리 중입니다. 잠시만 기다려 주세요!"
기타: "작업을 처리 중입니다. 잠시만 기다려 주세요!"
hideMsgModal()
모달과 오버레이를 제거합니다.
통합된 코드 예시
function performTaskExample() {
    // 1. 메시지 모달 표시
    showMsgModal(3);

    // 2. 작업 진행
    setTimeout(() => {
        console.log("작업 완료");
        
        // 3. 작업 완료 후 모달 숨기기
        hideMsgModal();
    }, 3000); // 작업을 3초간 시뮬레이션
}

// 함수 호출 예제
performTaskExample();
이점
showMsgModal로 이름을 변경함으로써 업로드뿐만 아니라 다양한 상황(예: 데이터 처리, 작업 진행)에서도 재사용 가능.
메시지 텍스트를 동적으로 설정하여 유연하게 사용 가능.





나의 말:
위의 코드에 버튼의 동작을 막는 기능을 주고, 다시 회복하는 내용도 들어가면 좋겠다.
ChatGPT의 말:
ChatGPT
아래는 showMsgModal 및 hideMsgModal 함수에 버튼의 동작을 막고 다시 회복시키는 기능을 추가한 코드입니다. 이 기능은 버튼을 비활성화하여 사용자 입력을 방지하고, 작업이 완료되면 다시 활성화합니다.

구현 코드
// 메시지 모달 표시 함수
function showMsgModal(type) {
    var message = '';
    switch (type) {
        case 1:
            message = '이미지를 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 2:
            message = '파일을 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 3:
            message = '데이터를 처리 중입니다. 잠시만 기다려 주세요!';
            break;
        default:
            message = '작업을 처리 중입니다. 잠시만 기다려 주세요!';
    }

    var modal = $('<div>').attr('id', 'msgModal').css({
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: '#fff',
        padding: '20px',
        borderRadius: '10px',
        boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)',
        zIndex: 10000,
        textAlign: 'center'
    }).text(message);

    var overlay = $('<div>').attr('id', 'msgOverlay').css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 9999
    });

    $('body').append(overlay).append(modal);

    // 모든 버튼 비활성화
    $('button').prop('disabled', true);
}

// 메시지 모달 숨기기 함수
function hideMsgModal() {
    $('#msgModal').remove();
    $('#msgOverlay').remove();

    // 모든 버튼 다시 활성화
    $('button').prop('disabled', false);
}

// 호출 예시
// 이미지를 업로드 중일 때
showMsgModal(1);
// 작업 완료 후 모달 닫기
hideMsgModal();
추가된 기능
버튼 비활성화:

showMsgModal 함수에서 모든 버튼(button 요소)을 비활성화(disabled) 상태로 만듭니다.
이를 통해 사용자가 작업 중 잘못된 동작을 하지 못하도록 방지합니다.
버튼 활성화:

hideMsgModal 함수에서 모든 버튼을 다시 활성화합니다.
작업 완료 후 정상적으로 동작을 복구합니다.
통합된 코드 예시
function performTaskExample() {
    // 1. 메시지 모달 표시 및 버튼 비활성화
    showMsgModal(3);

    // 2. 작업 진행
    setTimeout(() => {
        console.log("작업 완료");
        
        // 3. 작업 완료 후 모달 숨기기 및 버튼 활성화
        hideMsgModal();
    }, 3000); // 작업을 3초간 시뮬레이션
}

// 함수 호출 예제
performTaskExample();
결과
작업 시작 시 모든 버튼이 비활성화되어 동작이 차단됩니다.
작업 완료 후 버튼이 정상적으로 활성화됩니다.
showMsgModal과 hideMsgModal을 재사용하여 다양한 작업에서 동일한 로직을 적용할 수 있습니다.





나의 말:
추가적으로 해당 id가 있는지를 검사해서 있으면 처리하는 부분을 코드에 삽입해줘. 오류방지를 위해서다.
ChatGPT의 말:
ChatGPT
아래는 showMsgModal 및 hideMsgModal 함수에 ID 존재 여부를 검사하는 로직을 추가하여 오류를 방지한 코드입니다. 특정 ID가 이미 존재하면 새로 추가하지 않도록 설계했습니다.

수정된 코드
// 메시지 모달 표시 함수
function showMsgModal(type) {
    var message = '';
    switch (type) {
        case 1:
            message = '이미지를 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 2:
            message = '파일을 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 3:
            message = '데이터를 처리 중입니다. 잠시만 기다려 주세요!';
            break;
        default:
            message = '작업을 처리 중입니다. 잠시만 기다려 주세요!';
    }

    // 이미 모달이 표시 중이라면 중복 생성 방지
    if ($('#msgModal').length > 0 || $('#msgOverlay').length > 0) {
        return;
    }

    var modal = $('<div>').attr('id', 'msgModal').css({
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: '#fff',
        padding: '20px',
        borderRadius: '10px',
        boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)',
        zIndex: 10000,
        textAlign: 'center'
    }).text(message);

    var overlay = $('<div>').attr('id', 'msgOverlay').css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 9999
    });

    $('body').append(overlay).append(modal);

    // 모든 버튼 비활성화
    $('button').prop('disabled', true);
}

// 메시지 모달 숨기기 함수
function hideMsgModal() {
    // 모달이 없으면 처리 중단
    if ($('#msgModal').length === 0 || $('#msgOverlay').length === 0) {
        return;
    }

    $('#msgModal').remove();
    $('#msgOverlay').remove();

    // 모든 버튼 다시 활성화
    $('button').prop('disabled', false);
}

// 호출 예시
// 이미지를 업로드 중일 때
showMsgModal(1);
// 작업 완료 후 모달 닫기
hideMsgModal();
추가된 기능 설명
중복 생성 방지:

showMsgModal에서 #msgModal과 #msgOverlay ID를 검사합니다.
이미 해당 ID가 존재하면 함수 실행을 종료(return)하여 중복 생성되지 않도록 합니다.
존재 확인 후 삭제:

hideMsgModal에서 #msgModal과 #msgOverlay가 존재하는지 확인합니다.
없는 경우 처리 없이 종료하여 불필요한 오류를 방지합니다.
통합된 코드 예시
function performTaskExample() {
    // 1. 메시지 모달 표시 및 버튼 비활성화
    showMsgModal(3);

    // 2. 작업 진행
    setTimeout(() => {
        console.log("작업 완료");

        // 3. 작업 완료 후 모달 숨기기 및 버튼 활성화
        hideMsgModal();
    }, 3000); // 작업을 3초간 시뮬레이션
}



// 함수 호출 예제
performTaskExample();
결과
동일한 ID의 모달이 여러 번 생성되는 문제가 방지됩니다.
모달이 존재하지 않을 때 삭제를 시도해도 오류가 발생하지 않습니다.
더욱 안전한 코드 실행이 가능합니다.

최종코드 에디터로 제공

// 메시지 모달 표시 함수
function showMsgModal(type) {
    var message = '';
    switch (type) {
        case 1:
            message = '이미지를 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 2:
            message = '파일을 업로드 중입니다. 잠시만 기다려 주세요!';
            break;
        case 3:
            message = '데이터를 처리 중입니다. 잠시만 기다려 주세요!';
            break;
        default:
            message = '작업을 처리 중입니다. 잠시만 기다려 주세요!';
    }

    // 이미 모달이 표시 중이라면 중복 생성 방지
    if ($('#msgModal').length > 0 || $('#msgOverlay').length > 0) {
        return;
    }

    var modal = $('<div>').attr('id', 'msgModal').css({
        position: 'fixed',
        top: '50%',
        left: '50%',
        transform: 'translate(-50%, -50%)',
        backgroundColor: '#fff',
        padding: '20px',
        borderRadius: '10px',
        boxShadow: '0 0 10px rgba(0, 0, 0, 0.5)',
        zIndex: 10000,
        textAlign: 'center'
    }).text(message);

    var overlay = $('<div>').attr('id', 'msgOverlay').css({
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        backgroundColor: 'rgba(0, 0, 0, 0.5)',
        zIndex: 9999
    });

    $('body').append(overlay).append(modal);

    // 모든 버튼 비활성화
    $('button').prop('disabled', true);
}

// 메시지 모달 숨기기 함수
function hideMsgModal() {
    // 모달이 없으면 처리 중단
    if ($('#msgModal').length === 0 || $('#msgOverlay').length === 0) {
        return;
    }

    $('#msgModal').remove();
    $('#msgOverlay').remove();

    // 모든 버튼 다시 활성화
    $('button').prop('disabled', false);
}

// 호출 예시
// 이미지를 업로드 중일 때
showMsgModal(1);
// 작업 완료 후 모달 닫기
hideMsgModal();

활용해서 좋은 개발코드 만들어 보세요~

이것도 하나의 작품이네요~

반응형
댓글