[Angular] File Upload > Drag and Drop 만들기

안녕하세요. 명동섞어찌개입니다.
오늘은 Angular 를 이용한 파일 업로드 기능 개발 시 편리한 사용성을 위해 Drag and Drop 드래그 앤 드랍 기능을 추가하는 방법을 알아볼건데요,

vanila javascript (순수 자바스크립트) 로 개발하면 익스플로러와 크롬 브라우저 등 브라우저 별 예외처리가 필요해서 시간이 꽤 걸리는 일이지만 (개인적으로 0 부터 시작해서 개발했을 때 다른 업무 처리하면서 일주일 정도 걸렸습니다..) Angular 는 directive 를 사용해서 간편하게 개발할 수 있더라구요.

Angular Version: 8

결과화면



1. 먼저 drag-and-drop directive 를 만듭니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import {Directive, EventEmitter, Host, HostBinding, HostListener, Input, Output} from '@angular/core';

@Directive({
    selector: '[appDragDrop]'})
export class DragDropDirective {

    @Output() onFileDropped = new EventEmitter<any>();
    @Input('draggable') public draggable = true;

    @HostBinding('hintLine') public deco = false;
    @HostBinding('style.background-color') public background = '#fff';
    @HostBinding('style.opacity') public opacity = '1';

    //Dragover 시 스타일 정의    
    @HostListener('dragover', ['$event']) onDragOver(e) {
        e.preventDefault();
        e.stopPropagation();

        if(!this.draggable) return;

        this.background = '#ECF8FF';
        this.opacity = '0.8';
    }

    //Dragleave 시 스타일 정의    
    @HostListener('dragleave', ['$event']) public onDragLeave(e) {
        e.preventDefault();
        e.stopPropagation();
        this.background = '#fff';
        this.opacity = '1';
    }

    //Drop 시 받은 파일 목록을, 이 디렉티브를 사용하는 컴포넌트에 쏘아줍니다    
    @HostListener('drop', ['$event']) public ondrop(e) {
        e.preventDefault();
        e.stopPropagation();
        this.background = '#fff';
        this.opacity = '1';

        if(!this.draggable) return;

        let files = e.dataTransfer.files;
        if(files.length > 0) {
            this.onFileDropped.emit(files);
        }
    }

    constructor() {

    }

}



2. 만들어둔 파일 업로드 컴포넌트에 앞서 만든 드래그 앤 드롭 디렉티브를 적용해주면 끝
.html
1
2
3
<div class="dragAndDropZone dragZone" appDragDrop (onFileDropped)="onDropFiles($event)">
    <mat-icon fontSet="material-icons-outlined" class="mr5 color-midgray">note_add</mat-icon> 첨부할 파일을 마우스로 끌어서 추가할 수 있습니다.
</div>
.ts
1
2
3
4
5
onDropFiles( e ) {

    //파일 목록을 받아 처리

}

추가로 CSS 를 좀 더 매만져 예쁜 UI 를 만들어주시면 됩니다.

댓글

주간 인기글

카드뉴스 마케팅 팁

[ubuntu] 신규 계정에 sudo 권한 추가하기

SPA(Sigle Page Applications) 란 무엇인가?

안드로이드에서 당겨서 새로고침(SwipeRefreshLayout) 쉽게 구현하기

[AWS] WinSCP 를 이용해 Linux 인스턴스로 파일 전송하기