Files
sam-kd/KDunitprice/fileManager.js
hskwon aca1767eb9 초기 커밋: 5130 레거시 시스템
- URL 하드코딩 → .env APP_URL 기반 동적 URL로 변경
- DB 연결 하드코딩 → .env 기반으로 변경
- MySQL strict mode DATE 오류 수정
2025-12-10 20:14:31 +09:00

283 lines
11 KiB
JavaScript

// // 이미지 선택 이벤트 처리
// $("#upfileimage").change(function (e) {
// processFiles(this.files, tablename, "image", "upfileimage");
// });
// 파일 업로드 및 처리 함수
function processFiles(files, tablename, item, upfilename) {
var num = $("#num").val();
if (!files || files.length === 0) {
console.warn("파일이 선택되지 않았습니다.");
return;
}
showMsgModal(3); // 파일처리중
const formData = new FormData();
for (const file of files) {
formData.append(upfilename + "[]", file);
}
// 추가 데이터 설정
formData.append("tablename", tablename);
formData.append("item", item);
formData.append("upfilename", upfilename);
formData.append("folderPath", "uploads");
formData.append("DBtable", "picuploads");
formData.append("num", num);
// AJAX 요청
$.ajax({
url: "/filedrive/fileprocess.php",
type: "POST",
enctype: "multipart/form-data",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log("응답 데이터:", response);
let successCount = 0;
let errorCount = 0;
let errorMessages = [];
response.forEach((item) => {
if (item.status === "success") {
successCount++;
} else if (item.status === "error") {
errorCount++;
errorMessages.push(`파일: ${item.file}, 메시지: ${item.message}`);
}
});
if (successCount > 0) {
Toastify({
text: `${successCount}개의 파일이 성공적으로 업로드되었습니다.`,
duration: 2000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#4fbe87",
}).showToast();
}
if (errorCount > 0) {
Toastify({
text: `오류 발생: ${errorCount}개의 파일 업로드 실패\n상세 오류: ${errorMessages.join("\n")}`,
duration: 5000,
close: true,
gravity: "top",
position: "center",
backgroundColor: "#f44336",
}).showToast();
}
setTimeout(function () {
hideMsgModal();
if (item === "attached") displayFile();
if (item === "image") displayImage();
}, 1000);
},
error: function (jqxhr, status, error) {
console.error("업로드 실패:", jqxhr, status, error);
},
});
}
// 파일 불러오기
function displayFile() {
fetchFiles(tablename, "attached", "#displayFile");
}
// 이미지 불러오기
function displayImage() {
fetchFiles(tablename, "image", "#displayImage");
}
// 파일/이미지 데이터 가져오기
function fetchFiles(tablename, item, targetSelector) {
var tablename = $("#tablename").val();
const params = $("#num").val();
if (!params) {
console.error("ID 값이 없습니다. 데이터를 불러올 수 없습니다.");
return;
}
$.ajax({
url: "/filedrive/fileprocess.php",
type: "GET",
data: { num: params, tablename: tablename, item: item, folderPath: "uploads" },
dataType: "json",
success: function (data) {
console.log("데이터:", data);
$(targetSelector).html(""); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, index) {
const realName = fileData.realname || "다운로드 파일";
const link = fileData.link || "#";
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + index, fileData);
$(targetSelector).append(
"<div class='text-danger'>파일 ID가 누락되었습니다.</div>"
);
return;
}
$(targetSelector).append(
"<div class='row mt-1 mb-2'>" +
"<div class='d-flex align-items-center justify-content-center'>" +
"<span id='file" + index + "'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'filePopup', 800, 600); return false;\">" + realName + "</a>" +
"</span> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + index + "' onclick=\"deleteFile('" + index + "', '" + fileId + "', '" + tablename + "', '" + item + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$(targetSelector).append(
""
);
}
},
error: function (error) {
console.error("파일 불러오기 오류:", error);
},
});
}
function displayFileLoad() {
const data = <?php echo json_encode($savefilename_arr); ?>; // PHP에서 전달된 파일 배열
var tablename = $("#tablename").val();
$("#displayFile").html(""); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, index) {
const realName = fileData.realname || "다운로드 파일";
const link = fileData.link || "#";
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + index, fileData);
$("#displayFile").append(
"<div class='text-danger'>파일 ID가 누락되었습니다.</div>"
);
return;
}
$("#displayFile").append(
"<div class='row mt-1 mb-2'>" +
"<div class='d-flex align-items-center justify-content-center'>" +
"<span id='file" + index + "'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'filePopup', 800, 600); return false;\">" + realName + "</a>" +
"</span> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + index + "' onclick=\"deleteFile('" + index + "', '" + fileId + "', '" + tablename + "', 'attached')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayFile").append(
""
);
}
}
function deleteFile(index, fileId, tablename, item) {
Swal.fire({
title: "삭제 확인",
text: "정말 삭제하시겠습니까?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "삭제",
cancelButtonText: "취소",
reverseButtons: true,
}).then((result) => {
if (result.isConfirmed) {
showMsgModal(3); // 파일 처리 중 모달 표시
$.ajax({
url: "/filedrive/fileprocess.php",
type: "DELETE",
data: JSON.stringify({
fileId: fileId,
tablename: tablename,
item: item,
folderPath: "uploads",
DBtable: "picuploads",
}),
contentType: "application/json",
dataType: "json",
success: function (response) {
hideMsgModal(); // 처리 완료 후 모달 숨기기
if (response.status === "success") {
console.log("삭제 완료:", response);
$("#file" + index).remove(); // 파일 요소 삭제
$("#delFile" + index).remove(); // 삭제 버튼 삭제
Swal.fire("삭제 완료", "파일이 성공적으로 삭제되었습니다.", "success");
} else {
Swal.fire("삭제 실패", response.message || "알 수 없는 오류가 발생했습니다.", "error");
}
},
error: function (error) {
hideMsgModal(); // 오류 발생 시 모달 숨기기
console.error("삭제 실패:", error);
Swal.fire("삭제 실패", "파일 삭제 중 문제가 발생했습니다.", "error");
},
});
}
});
}
// 기존 이미지 로드 함수
function displayImageLoad() {
const data = <?php echo json_encode($saveimagename_arr); ?>; // PHP에서 전달된 이미지 배열
var tablename = $("#tablename").val();
$("#displayImage").html(""); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, index) {
const realName = fileData.realname || "다운로드 파일";
const thumbnail = fileData.thumbnail || "/assets/default-thumbnail.png";
const link = fileData.link || "#";
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + index, fileData);
$("#displayImage").append(
"<div class='text-danger'>파일 ID가 누락되었습니다.</div>"
);
return;
}
$("#displayImage").append(
"<div class='row mb-3'>" +
"<div class='d-flex align-items-center justify-content-center'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'imagePopup', 800, 600); return false;\">" +
"<img id='image" + index + "' src='" + thumbnail + "' style='width:150px; height:auto;'>" +
"</a> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + index + "' onclick=\"deleteFile('" + index + "', '" + fileId + "', '" + tablename + "', 'image')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayImage").append(
""
);
}
}