본문 바로가기

Devexpress

Devexpress 드래그로 이미지 업로드 구현, dxFileUploader()

프로필을 선택하면 팝업을 띄우고, 이후 프로필을 변경할 수 있게 구현해봤다.

 

우선 View에서 프로필 사진을 누르면 팝업이 뜨게 해줬다.

<div id="popup-profile-click2" class="id-menu-img-box"><img src="@profilePicturePath" alt="프로필 사진" /></div>


<div id="popup-profile"></div>
<div id="popup-profile2"></div>

 

$('#popup-profile-click2').click(function(){
	$('#popup-profile2').dxPopup({
            title: "프로필사진",
            visible: true,
            hideOnOutsideClick: true,
            height: "550px",
            maxWidth: "550px",
            contentTemplate: function () {
                return `
                    <div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">  
                        <div style="width:400px;height:400px;display: flex; align-items: center; justify-content: center; border: 1px solid black;box-shadow: 0px 0px 10px rgba(0,0,0,0.15); border-radius: 10px;">
                            <img src="${path_1}" alt="프로필 사진" style="max-width:100%; max-height:100%;" />
                        </div>
                        <hr/>
                        <div id="popup-profile-click"><i class="bi bi-camera-fill"></i>프로필변경하기</div>
                    </div>
                `;
            }
            
        })
})

 

dxPopup() 에서 프로필 변경하기를 누르면 confirm으로 확인 받고 작동하게 해줬다.

 

dxFileUploader() 을 사용해서 이미지 업로드를 구현했다.

기본 제공하는 dragpool 예제에서 가져왔고, 

주의할 점이 multiple : false로 가져오면

name을 "files" 로 바꿔야한다. (기본 "files[]")

useloadMode 에서 uploadFile을 언제할지 정할 수 있고,

uploadUrl 에서 백단에서 처리할 주소를 적어주면 된다.

 

$('#popup-profile-click').click(function () {

    if (confirm('프로필 사진을 변경하시겠습니까?')) {
        $('#popup-profile').dxPopup({
            title: "프로필 사진을 선택해주세요",
            visible: true,
            hideOnOutsideClick: true,
            height: "550px",
            maxWidth: "550px",
            contentTemplate: function () {
                return `
                            <div class="mem_info2">
                                <h3>프로필 변경</h3>
                                <div class="mem_sub2">
                                    <div class="form_box">
                                        <div class="demo-container">
                                            <div class="widget-container flex-box">
                                                <div id="dropzone-external2" class="flex-box dx-theme-border-color">
                                                    <img id="dropzone-image2" src="#" hidden alt="" />
                                                    <div id="dropzone-text2" class="flex-box">
                                                        <span>파일을 드래그하거나 버튼을 눌러 등록해주세요.</span>
                                                        <span><br/>새로 로그인 하시면 변경된 프로필이 적용됩니다.</span>
                                                    </div>
                                                    <div id="upload-progress2"></div>
                                                </div>
                                                <div id="file-uploader2"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
            }
        });
        $(() => {

            $('#file-uploader2').dxFileUploader({
                dialogTrigger: '#dropzone-external2',
                dropZone: '#dropzone-external2',
                multiple: false, // 여러개 파일
                allowedFileExtensions: ['.jpg', '.jpeg', '.gif', '.png'],
                uploadMode: 'instantly', //useButtons, useForm
                uploadUrl: '보낼주소결정', // 이거 설정
                uploadMethod: 'POST',
                uploadDirectory: '/Images',
                visible: false,
                name: "files", // 기본 "files[]"

                onDropZoneEnter(e) {
                    if (e.dropZoneElement.id === 'dropzone-external') { toggleDropZoneActive(e.dropZoneElement, true); }
                },
                onDropZoneLeave(e) {
                    if (e.dropZoneElement.id === 'dropzone-external') { toggleDropZoneActive(e.dropZoneElement, false); }
                },
                onUploaded(e) {
                    const { file } = e;
                    const dropZoneText = document.getElementById('dropzone-text2');
                    const fileReader = new FileReader();
                    fileReader.onload = function () {
                        toggleDropZoneActive(document.getElementById('dropzone-external2'), false);
                        const dropZoneImage = document.getElementById('dropzone-image2');
                        dropZoneImage.src = fileReader.result;
                    };
                    fileReader.readAsDataURL(file);
                    dropZoneText.style.display = 'none';
                    uploadProgressBar.option({
                        visible: false,
                        value: 0,
                    });

                    alert('프로필 사진을 변경합니다!');
                    window.location.reload();
                },
                onProgress(e) {
                    uploadProgressBar.option('value', (e.bytesLoaded / e.bytesTotal) * 100);
                },
                onUploadStarted() {
                    toggleImageVisible(false);
                    uploadProgressBar.option('visible', true);
                },
            });

            const uploadProgressBar = $('#upload-progress2').dxProgressBar({
                min: 0,
                max: 100,
                width: '30%',
                showStatus: false,
                visible: false,
            }).dxProgressBar('instance');

            function toggleDropZoneActive(dropZone, isActive) {
                if (isActive) {
                    dropZone.classList.add('dx-theme-accent-as-border-color');
                    dropZone.classList.remove('dx-theme-border-color');
                    dropZone.classList.add('dropzone-active');
                } else {
                    dropZone.classList.remove('dx-theme-accent-as-border-color');
                    dropZone.classList.add('dx-theme-border-color');
                    dropZone.classList.remove('dropzone-active');
                }
            }

            function toggleImageVisible(visible) {
                const dropZoneImage = document.getElementById('dropzone-image2');
                dropZoneImage.hidden = !visible;
            }

            document.getElementById('dropzone-image2').onload = function () { toggleImageVisible(true); };
        });
    }
    else {
        alert('프로필 사진 변경을 취소합니다!');
    }
})

 

백단으로 주소를 보내면 아래처럼 받는다.

이후 원하는 로직을 처리하면 된다.

아래 두 개는 파일명과 확장자를 가져오는 코드이다.

public async Task<ActionResult> UserProfileUpload(IFormFile files)
{
    // 이름가져오기
    string fileName = Path.GetFileNameWithoutExtension(files.FileName);
    // 확장자
    string fileExtension = Path.GetExtension(files.FileName).ToLower();

'Devexpress' 카테고리의 다른 글