파일을 Drag&Drop 하여 업로드할 수 있도록 구현해보겠습니다.
vue2-dropzone 3.6.0 버전, vue 2 버전 사용하였습니다.
1. vue2-dropzone download
npm install vue2-dropzone
- Github 링크 : https://rowanwins.github.io/vue-dropzone/docs/dist/#/installation
2. HTML
<vue-dropzone
id="drop-file"
:options="dropOption"
@vdropzone-file-added="addFile"
@vdropzone-removed-file="removeFile"
></vue-dropzone>
- id는 drop-file로 줬습니다.
- options 값은 dropOption으로 데이터를 따로 모아 넘겼습니다.
- vdropzone-file-added는 파일이 드롭존에 추가되었을 때 발생하는 이벤트입니다.
- vdropzone-removed-file은 드롭존에 올라간 파일을 삭제했을 때 발생하는 이벤트입니다.
3. option data
dropOption: {
url: url 입력,
params: { 파라미터 입력 },
acceptedFiles: ".mp4,.wmv,.jpg,.jpeg,.png,.bmp",
method: "post",
autoProcessQueue: false,
maxFiles: 5,
thumbnailWidth: 150,
thumbnailHeight: 150,
addRemoveLinks: true,
dictRemoveFile: "삭제",
dictCancelUpload: "취소",
dictCancelUploadConfirmation: "파일 업로드를 취소하시겠습니까?",
dictDefaultMessage: "Drag&Drop or Click!!",
init: function () {
this.on("error", function (file, errorMessage, xhr) {
this.removeFile(file);
if (errorMessage === "You can't upload files of this type.") {
alert("업로드가 불가능한 파일 형식입니다.");
} else if (errorMessage === "You can not upload any more files.") {
alert("파일은 최대 5개까지 업로드할 수 있습니다.");
}
});
},
},
- 파일 업로드 url과 추가로 넘겨줄 파라미터를 url, params에 넣어줍니다.
- acceptedFiles는 업로드가 가능한 파일 확장자를 정의합니다.
- 위에 입력한 url을 통해 바로 업로드가 가능하지만, 저는 autoProcessQueue를 false로 줘서 따로 업로드 메서드를 구현했습니다.
- maxFiles는 5로 설정하여 최대 업로드 개수를 5개로 설정했습니다.
- dropzone에 보일 썸네일 크기는 thumbnailWidth와 thumbnailHeight로 정할 수 있습니다.
- addRemoveLinks를 true로 하여 드롭존에 올라간 파일을 삭제할 수 있게 했습니다.
- dict~ 로 되어있는 값들은 디폴트로 입력된 문구들을 변경한 것입니다.
- init에는 함수를 선언할 수 있는데, 저는 error가 발생한 경우 중 두 가지 경우를 처리했습니다.
4. Method 구현
addFile(file) {
this.files.push(file);
},
removeFile(file, error, xhr) {
this.files = this.files.filter((f) => f.upload.fid !== file.upload.fid);
},
async uploadFiles() {
// 파일 업로드 서비스 호출
},
- files라는 빈 배열을 하나 선언해서 파일이 추가될 때 push, 파일이 삭제될 때 filter로 걸러 파일 목록을 저장했습니다.
- 저는 드래그 앤 드롭을 팝업창에 띄웠기 때문에 팝업에서 저장 버튼을 누를 때만 uploadFiles 메서드가 호출되도록 했습니다. 그렇기 때문에 저장 버튼을 누르지 않으면 서버 및 데이터베이스에 저장되지 않습니다.
5. CSS Style
.dropzone .dz-preview .dz-progress {
height: 0 !important;
}
- autoProcessQueue를 false로 줬기 때문에 progress 바가 마치 로딩이 안 된 것처럼 떠서 스타일로 삭제해버렸습니다.
이상으로 Drag&Drop으로 파일 업로드하는 기능을 구현해보았습니다.
'Web Developer's Story > VUE.js' 카테고리의 다른 글
[Vue.js] vue3 cryptoJS sha256 비밀번호 암호화, 정규식 조건 설정 (3) | 2024.08.28 |
---|---|
[Vue.js] styled components 사용법 (0) | 2023.01.12 |
[Vue.js] vue-carousel 사용법 및 navigation custom (0) | 2022.11.24 |
[Vue.js] transition-group 양방향 slide navigation 구현 (2) | 2022.10.05 |
[Vue.js] vue2-datepicker 일간(day), 주간(week), 월간(month) 사용법 (0) | 2022.09.29 |