기본 콘텐츠로 건너뛰기

[javascript] drag and drop을 이용하여 파일 업로드를 해보자

이번 포스팅에서는 서버 쪽이 아닌 프론트 단에서 파일 업로드를 하는 방법에 대해서 알아보려고 한다.
input에 type을 file로 하면 매우 쉽게 가능하지만 단순한 파일 선택이 아닌 로컬 컴퓨터에 존재하는 파일을 drag and drop을 이용하여 파일을 추가하는 방법에 대해서 알아보려고 한다.
우선 서버 쪽에서 파일을 처리하는 부분은 이전에 글을 작성한 적이 있으므로 이전 글을 참고하길 바란다.

[node.js] multer 2 - array, field방법

[node.js] multer를 이용한 파일 업로드 - single방법

<form id="upload" action="/note/upload" method="POST" enctype="multipart/form-data"> <fieldset> <div class="files"> <input id="fileselect" type="file" name="fileselect" multiple="multiple" class="addFile"/> </div> <div id="filedrag">drag and drop</div> <div id="submitbutton"> <button type="submit">Upload Files</button> </div> </fieldset> </form> <table class="table"> <thead> <th>이름</th> <th>타입</th> <th>용량</th> </thead> <tbody id="list"></tbody> </table>
필자는 files라는 속성을 찾는데 2시간가량이 걸렸던 것 같다... 파일 추가는 됐는데 자꾸 파일 객체가 추가가 안돼서 서버 측에서 파일을 제대로 받지 못하는 상황이 있었고 검색을 하다 보니 files라는 속성값이 있다는 것을 찾아냈다. 아래 스크립트는 파일을 drag and drop을 할 때마다 동적으로 파일을 추가하는 스크립트이다.
코드 자체에서 크게 어려운 점은 없다.

drop 이벤트 발생 -> input 추가 -> 가장 마지막 input에 drop된 파일 객체 추가.

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
 * Created by bagjeongtae on 2017. 5. 9..
 */
// getElementById
function $id(id) {
    return document.getElementById(id);
}
// output information
function Output(msg) {
    var m = $id("list");
    m.innerHTML = msg + m.innerHTML;
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
    Init();
}
// initialize
function Init() {
    var fileselect = $id("fileselect"),
        filedrag = $id("filedrag"),
        submitbutton = $id("submitbutton");
    // file select
    fileselect.addEventListener("change", FileSelectHandler, false);
    // is XHR2 available?
    var xhr = new XMLHttpRequest();
    if (xhr.upload) {
        // file drop
        filedrag.addEventListener("dragover", FileDragHover, false);
        // filedrag.addEventListener("dragleave", FileDragHover, false);
        filedrag.addEventListener("drop", FileSelectHandler, false);
        filedrag.style.display = "block";
        // remove submit button
        submitbutton.style.display = "none";
    }
}
// file drag hover
function FileDragHover(e) {
    e.stopPropagation();
    e.preventDefault();
    e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
    // cancel event and hover styling
    FileDragHover(e);
    // fetch FileList object
    var files = e.target.files || e.dataTransfer.files;
    console.log('te');
    addFileFromLastInput(files);
    // process all File objects
    for (var i = 0, f; f = files[i]; i++) {
        ParseFile(f);
    }
}
function ParseFile(file) {
    var fileName = file.name,
        fileType = file.type,
        fileSize = file.size + 'bytes';
    Output(
        '<tr><td>' + fileName +
        '</td><td>' + fileType +
        '</td><td>' + fileSize +
        '</td> </tr>'
    );
}
function addFileFromLastInput(file){
    var a = $("input#fileselect.addFile");
    a[a.length-1].files = file;
    try{
        let new_input = <input id="fileselect" type="file" name="fileselect" multiple="multiple" class="addFile" />;
        $(".files").append(new_input);
    }catch(err){
    }
    return 0;
}
cs

drop 이벤트를 통해서 해당 파일이 특정 dom 안에 떨어졌을 경우 이벤트를 잡을 수 있다.
var files = e.target.files || e.dataTransfer.files;
drop된 객체에서 file 객체 가져오기 
var a = $('input#fileselect.addFile'); a[a.length-1].files = file;
가장 마지막 input에 drop된 file 객체 추가
css는 알아서 취향에 맞춰서 작성을 하면됩니다 ㅋㅋㅋ

댓글

이 블로그의 인기 게시물

[node.js] 파일 리더기 만들기 - 사용 모듈 정리, pdf 구조, hwp 구조

pdf -> html 변환 가장 무난하다. 기본적으로 pdf는 htm와 비슷한 형태의 구조를 가지고 있다. 크게 header , body , xref table , trailer 의 구조로 되어있다. pdf는 환경에 상관없이 표현을 하기 위한 목적을 가지고 있는 파일이다. 이런 이유 때문에 무난히 진행이 된 것 같다. pdf2htmlex와 pdftohtmljs라는 모듈을 이용을 했다. var pdftohtml = require ( 'pdftohtmljs' ) ; var converter = new pdftohtml ( 'test.pdf' , "sample.html" ) ; converter . convert ( 'ipad' ) . then ( function ( ) { console . log ( "Success" ) ; } ) . catch ( function ( err ) { console . error ( "Conversion error: " + err ) ; } ) ; 이미지나, text같은 것들이 거의 100%로 변환이 된다. docx -> html 변환 docx파일을 html파일로 변환을 할 때는 style 적용과 한글이 깨지는 문제가 있다. 텍스트들을 전부 잘 읽기는 하는데 스타일 정보를 제대로 가져오지 못하기 때문에 좀 애매하다 - Headings. - Lists. - Customisable mapping from your own docx styles to HTML. For instance, you could convert WarningHeading to h1.warning by providing an appropriate style ...

[css] css로 프린트 방지하기

웹에서 프린트 제어가 불가능 한 줄 알았는데 프린트 클릭 시  스크립트로 해당 이벤트를 받아올 수 있다. 하지만 스크립트를 사용하는 방법은 브라우저마다 작동을 하지 않을 수 있다. 좀 더 찾아보니 css로 인쇄되는 영역을 제어를 해줄 수 있다.  @media print 를 이용하면 된다. < html > < head > < title > print test page < / title > < style > @media print { . np { display : none ; } } < / style > < / head > < body > < div class = "np" > test < / div > < div > test1 < / div > < div > test1 < / div > < div > test1 < / div > < / body > < / html > 위 코드를 보면 np 클래스를 @media print에 넣어주었다. @media print는 인쇄됐을 때의 스타일을 지정을 해주는 것이다.  위에서는 해당 페이지를 인쇄할 때 p를 display : none으로 가려주었다. @media print를 이용하면 좀 더 멋진 인쇄물을 만들 수 ...

[알고리즘] snake게임 알고리즘

막무가네로 알고리즘을 공부하면 재미가 없으니 게임을 접목하여 다루어 보도록 하겠습니다. 게임의 대상은 스네이크 게임입니다. 많은 사람들은 어릴 때 뱀게임을 많이 해봤을 것 입니다. 이번에 다뤄볼 주제는 뱀이 움직임을 어떻게 구현을 할지 알아보겠습니다. 뱀은 크게 3가지의 경우가 있습니다 1. 가장 중요한 뱀을 움직이기 2. 음식먹기 이때 뱀은 크기가 늘어나야 합니다. 3. 뱀이 움직이는 정책   - 뱀이 움직이지 못하는 경우는 : 우측방향에서 좌측 방향으로 OR 위에 아래 방향고 같이 180도 반전되는 움직임은 막겠습니다. 순수한 알고리즘을 만드는 과정이기 때문에 음식을 먹었는지 안먹었는지 판단하는 부분은 랜덤으로 판단을 하도록 하겠습니다. def is_eat(): return random.choice([1, 0]) 랜덤으로 1, 0을 반환을 해줍니다. 실제로 게임을 만든다면 해당 함수는 뱀의 머리가 음식의 좌표와 같은지 검사를 해주면 되겠습니다. key_position_map = { 'w': [-1, 0], # up 's': [1, 0], # down 'a': [0, -1], # left 'd': [0, 1] # right } direction = key_position_map.get('d') 다음으로는 키맵핑을 한 오브젝트 입니다. direction은 현재 뱀의 방향을 나타냅니다. snake_body = [[2, 3], [1, 3],[1, 2], [1, 1]] 주인공이 되는 뱀의 좌표들 입니다. while True: key = input() new_direction = key_position_map.get(key) if new_direction and direction_check(direction, new_direction): directi...