본문 바로가기
javascript

[js] 이미지(blob) 업로드

by TTTGGG 2024. 8. 16.
728x90
반응형
SMALL

DB Column 정보 (mariadb)

<!-- 이미지 업로드 섹션 -->
<div class="row mb-3">
    <div class="col-md-12">
        <label for="fileImage" class="form-label">이미지 업로드</label>
        <div class="row">
            <div class="col-9">
                <input type="file" id="fileImage" class="form-control" accept="image/*" onchange="PreviewImage(event)" />
            </div>
            <div class="col-3">
                <button type="button" id="btnRemoveImage" class="btn btn-danger w-100">이미지 제거</button>
            </div>
        </div>
    </div>
    <div class="col-md-12 mt-3">
        <img id="imgPreview" src="#" alt="이미지 미리보기" style="display:none; width: 100%; max-height: 300px;" />
    </div>
</div>

<script>
	let image = "";
    
    // 이미지 미리보기  
    function PreviewImage(event) {
        const reader = new FileReader();
        reader.onload = function () {
            const output = document.getElementById('imgPreview');
            output.src = reader.result;
            output.style.display = 'block';

            // 이미지를 Base64로 인코딩하여 저장
            image = reader.result.split(',')[1];  // Base64 데이터 부분만 추출
        };
        reader.readAsDataURL(event.target.files[0]);
    }
    
    fnInsertData = function () {
		...
        
		// 컨트롤러에 전송
        $.post({
            type: 'POST',
            url: '/Controller/Add',
            data: serializedData,
            success: function (data) {
				// 성공 시 이벤트
                }
            }, error: function (xhr) {
				// 실패 시 이벤트 
            }
        });
    }    
</script>

 

결과

728x90
반응형
LIST