
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
/**
* 에디터 파일 업로드를 활용한 파일 업로더
* $.initFileUpload(options, [createDom])
*/
;
(function($) {
var defaults = {
fileListDivId : 'fileListDivId',
inputFileId : 'inputFileId',
hiddenFileName : 'hiddenFileName',
progress : 'progress',
maxSize : 5, // 첨부파일 등록개수
fileAllowedTypes: ['*'], // 확장자 체크 ['png', 'pdf']
fileMaxSize: 10, // 첨부파일 사이즈 MB단위
deleteButton: true, // deleteButton 사용유무
authorType : 'admin' // 파일 목록 디자인(사용자, 관리자)
}
$.initFileUpload = function(options, createDom) {
options = $.extend({}, defaults, options);
if (createDom != null) { // 파일 목록 생성 DOM override
defaultsDom = $.extend(createDom, defaultsDom);
}
// hiddenFileName 변경 이벤트
$('input[name="' + options.hiddenFileName + '"]').on('change', function() {
fncSelectFile($(this).val());
});
// 기존파일 데이터 생성(수정 시)
var hiddenId = $('input[name="' + options.hiddenFileName + '"]').val();
if (hiddenId != null && hiddenId != '') {
fncSelectFile(hiddenId);
}
// fileId로 데이터 조회
function fncSelectFile(hiddenId) {
if (hiddenId != null && hiddenId != '') {
$.ajax({
method : "POST",
url : CONTEXT_PATH +"/editor/fileList.do",
data : {
fileId : hiddenId
}
}).done(function(data) {
// 파일 데이터 생성
for (var i = 0; i < data.length; i++) {
var html = data[i];
var dom = '';
if (options.authorType == 'user') {
dom = defaultsDomUser(html);
$('.file_list_wrap').addClass("show");
} else {
dom = defaultsDom(html, options);
}
$('#' + options.fileListDivId).append(dom);
// 업로드시 div 표시
$('#' + options.fileListDivId).removeAttr('style');
// 이벤트 추가(파일삭제)
fncFileTrigger(html);
}
}).fail(function(err) {
// console.log ('file delete problem: ' + JSON.stringify(err));
})
}
}
// 갯수제한
fncMaxLength(options);
// 특정 파일 확장자만 지정
if( options.fileAllowedTypes.indexOf('*') == -1 ) {
var ext = '';
$(options.fileAllowedTypes).each(function(i) {
if( i > 0 ) {
ext += ",";
}
ext += '.' + this;
});
$('#' + options.inputFileId).attr('accept', ext);
}
// input file 업로드 이벤트
$('#' + options.inputFileId).on('change', function() {
if ($(this).val()) {
fncFileUp(options);
}
});
// input file 설정
var fileTarget = $('.filebox .upload-hidden');
fileTarget.on('change', function() { // 값이 변경되면
if (window.FileReader) { // modern browser
var filename = $(this)[0].files[0].name;
} else { // old IE
var filename = $(this).val().split('/').pop().split('\\').pop(); // 파일명만
// 추출
} // 추출한 파일명 삽입
$(this).siblings('.upload-name').val(filename);
});
// 파일 업로드
var fncFileUp = function(options) {
var data = new FormData();
var file = $('#' + options.inputFileId)[0].files[0];
// 확장자 및 용량체크
if( !fncValidate(options, file) ) {
return;
};
data.append("file", file);
$.ajax({
type : 'post',
url : CONTEXT_PATH + '/editor/uploadFile.do',
data : data,
processData : false,
contentType : false,
beforeSend : function() {
if(options.progress == "progress"){
$.blockUI();
}
},
complete : function() {
if(options.progress == "progress"){
$.unblockUI();
}
},
success : function(html) {
// FileUploadInterceptor에서 필러링 처리
if( html.fileId == null ) {
$('#' + options.inputFileId).val("");
alert ('허용되지 않은 확장자입니다.');
return;
}
var dom = '';
if (options.authorType == 'user') {
dom = defaultsDomUser(html);
$('.file_list_wrap').addClass("show");
} else {
dom = defaultsDom(html, options);
}
$('#' + options.fileListDivId).append(dom);
// 업로드시 div 표시
$('#' + options.fileListDivId).removeAttr('style');
// 이벤트 추가(파일삭제)
fncFileTrigger(html);
var atch_id = $('input[name="' + options.hiddenFileName + '"]').val();
if (atch_id.length == 0) {
atch_id = html.fileId;
} else {
atch_id = atch_id + "," + html.fileId;
}
$('input[name="' + options.hiddenFileName + '"]').val(atch_id);
$('#' + options.inputFileId).val("");
// 갯수제한
fncMaxLength(options);
},
error : function(error) {
alert("파일 업로드에 실패하였습니다.");
console.log(error);
console.log(error.status);
},
xhr : function() { // 프로그래스
var xhr = new window.XMLHttpRequest();
// 업로드 중 프로그래스바 표시
$('#' + options.progress).removeAttr('style');
$('#' + options.progress).find('.progress-bar').attr('style', 'width: 0%');
$('#' + options.progress).find('.progress-bar').text('0%');
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
// 프로그래스바 이동
$('#' + options.progress).find('.progress-bar').attr('style', 'width: ' + percentComplete + '%');
$('#' + options.progress).find('.progress-bar').text(percentComplete + '%');
if (percentComplete === 100) {
$('#' + options.progress).attr('style', 'display: none;');
}
}
}, false);
return xhr;
},
});
}
// 파일 이벤트 추가(삭제)
var fncFileTrigger = function(html) {
$('#' + html.fileId).find('button:eq(0)').on('click', function() {
fncUnlink(options, html.link);
});
}
// 링크 삭제(파일 삭제)
var fncUnlink = function(options, link) {
$.ajax({
// Request method.
method : "POST",
// Request URL.
url : CONTEXT_PATH +"/editor/deleteFile.do",
// Request params.
data : {
src : link
}
}).done(function(data) {
// console.log ('file was deleted');
// 링크 삭제시 파일 목록 삭제
if (options.fileListDivId != '') {
var atch_id = $('input[name="' + options.hiddenFileName + '"]').val();
var new_atch_id = "";
for (i = 0; i <= atch_id.split(',').length - 1; i++) {
if (atch_id.split(',')[i] != data.fileId) {
if (atch_id.split(',').length != 1) {
if (new_atch_id == "") {
new_atch_id = atch_id.split(',')[i];
} else {
new_atch_id = new_atch_id + "," + atch_id.split(',')[i];
}
}
}
}
// 첨부파일 목록 파일 삭제
$('#' + data.fileId).remove();
var $nextFocus = $('#' + options.fileListDivId).find('li').eq(1);
if ($nextFocus.length > 0) {
$nextFocus.find('button:eq(0)').focus();
} else {
$('#' + options.fileListDivId).find('li input[type="file"]:eq(0)').focus();
}
// 실제 넘기는 파일(hidden파일)
$('input[name="' + options.hiddenFileName + '"]').val(new_atch_id);
// 파일 없을 시 div 감춤
if (new_atch_id == '') {
//제품,기술 이미지 등록 시 예외
if(options.fileListDivId != 'reprsntImgFile' && options.fileListDivId != 'subImgFileList')
$('#' + options.fileListDivId).attr('style', 'display:none;');
}
// 업로드된 파일명 제거
$('.filebox .upload-hidden').siblings('.upload-name').val("파일선택");
// 갯수제한
fncMaxLength(options);
}
}).fail(function(err) {
// console.log ('file delete problem: ' + JSON.stringify(err));
})
}
};
// 파일 목록 생성
var defaultsDom = function(html, options) {
var deleteButton = options.deleteButton;
var dom = '<div id=' + html.fileId + ' style="margin-top: 5px;">';
dom += '<span style="line-height: 30px; margin-left: 10px;">';
dom += html.originFileNm;
dom += '</span>';
dom += '<div class="fr" style="margin-right: 2px;">';
var display = '';
if (!deleteButton) {
display = ' display: none;';
}
// dom += '<a class="btn_sq_s btn_delete mr2"' + display + '" href="javascript:void(0)" title="삭제 버튼"><em class="blind">삭제</em></a> ';
dom += '<button type="button" class="btn_sq_s btn_delete mr2"' + display + '" onclick="javascript:void(0)" title="삭제 버튼"><em class="blind">삭제</em></button> ';
dom += '<a class="btn_sq_s btn_filedown" href="' + html.link + '" title="파일 다운로드 버튼"><em class="blind">파일 다운로드</em></a></a>';
dom += '<button type="button" class="btn_sq_s btn_filedown" href="' + html.link + '" onclick="location.replace(' + "'" + html.link + "'" + ');" title="파일 다운로드 버튼"><em class="blind">파일 다운로드</em></button>';
dom += '</div>';
dom += '</div>';
return dom;
}
// 파일 목록 생성 (사용자게시판)
var defaultsDomUser = function(html) {
var dom = '<div class="file_list" id="'+html.fileId+'">'
+ '<p class="filename">'+html.originFileNm+'</p>'
+ '<button type="button" class="btn_delete btn_sq_s" title="등록된 파일 삭제" >삭제</button>'
+ '<button type="button" class="btn_ss bg_basic" title="등록된 파일 본문에 넣기" style="margin-left:3px;">본문에 넣기</button>'
+ '</div>'
+ '<div class="space5"></div>';
return dom;
}
// 개수 제한
var fncMaxLength = function(options) {
var atch_id = $('input[name="' + options.hiddenFileName + '"]').val();
if(atch_id){
var size = atch_id.split(',').length;
if( atch_id.length == 0 ) {
size = 0;
}
if( options.maxSize > size ) {
$('#' + options.inputFileId).prop('disabled', false);
} else {
$('#' + options.inputFileId).prop('disabled', true);
}
}else{
$('#' + options.inputFileId).prop('disabled', false);
}
}
// 확장자 체크 및 용량 체크
var fncValidate = function(options, file) {
if( options.fileAllowedTypes.indexOf('*') == -1 ) {
var ext = file.name.split('.').pop().toLowerCase();
if( $.inArray(ext, options.fileAllowedTypes) == -1 ) {
alert('허용되지 않은 확장자입니다.');
$('#' + options.inputFileId).val("");
return false;
}
}
if( options.fileMaxSize > -1 ) {
var fileSize = file.size;
var maxSize = options.fileMaxSize * 1024 * 1024;
if( fileSize > maxSize ) {
alert('파일 사이즈는 ' + fileSizeConvert(maxSize) + '이내로 등록 가능합니다.');
$('#' + options.inputFileId).val("");
return false;
}
}
return true;
}
})(jQuery);
//파일 확장자별 아이콘
function fileExtIcon(extsn) {
var fileExtsn = extsn;
var fileIcon = 'far fa-file';
switch (fileExtsn) {
case 'pdf':
fileIcon = 'far fa-file-pdf';
break;
case 'ppt':
fileIcon = 'far fa-file-powerpoint';
break;
case 'pptx':
fileIcon = 'far fa-file-powerpoint';
break;
case 'xls':
fileIcon = 'far fa-file-excel';
break;
case 'xlsx':
fileIcon = 'far fa-file-excel';
break;
case 'doc':
fileIcon = 'far fa-file-word';
break;
case 'docx':
fileIcon = 'far fa-file-word';
break;
case 'hwp':
fileIcon = 'far fa-file-word';
break;
case 'png':
fileIcon = 'far fa-file-image';
break;
case 'jpg':
fileIcon = 'far fa-file-image';
break;
case 'jpeg':
fileIcon = 'far fa-file-image';
break;
case 'gif':
fileIcon = 'far fa-file-image';
break;
case 'bmp':
fileIcon = 'far fa-file-image';
break;
case 'zip':
fileIcon = 'far fa-file-archive';
break;
case '7z':
fileIcon = 'far fa-file-archive';
break;
default:
fileIcon = 'far fa-file';
}
return fileIcon;
}
// 파일 사이즈 변경
function fileSizeConvert(size) {
var fileSize = size;
if (fileSize / 1024 >= 1024) {
fileSize = (fileSize / (1024 * 1024)).toFixed(1) + "MB";
} else {
fileSize = (fileSize / 1024).toFixed(1) + "KB";
}
return fileSize;
}