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

570 lines
20 KiB
PHP

<script>
var ajaxRequest11 = null;
$(document).ready(function () {
displayFileLoad(); // 기존파일 업로드 보이기
displayImageLoad(); // 기존이미지 업로드 보이기
// displayImageLoad(); // 기존 이미지 로드
var tablename = $("#tablename").val();
const uploadedFiles = new Set(); // 업로드된 파일 이름을 저장하는 Set
// 드롭 영역 설정
const dropArea = $("#dropArea");
dropArea.on("dragover", function (e) {
e.preventDefault();
dropArea.css("border-color", "blue"); // 드래그 중 표시
});
dropArea.on("dragleave", function (e) {
e.preventDefault();
dropArea.css("border-color", "#ccc"); // 드래그 해제 시 원래대로
});
dropArea.on("drop", function (e) {
e.preventDefault();
dropArea.css("border-color", "#ccc"); // 드롭 시 원래대로
const files = e.originalEvent.dataTransfer.files;
if (files.length > 0) {
processFiles(files, tablename, "attached", "upfile");
}
});
// 파일 선택 이벤트 처리
$("#upfile").off("change").on("change", function (e) {
e.preventDefault();
const files = this.files;
console.log('upfile ', files);
if (files.length > 0) {
filterAndProcessFiles(files, tablename, "attached", "upfile");
}
});
// 중복 파일 필터링 및 처리 함수
function filterAndProcessFiles(files, tablename, type, inputId) {
const newFiles = [];
for (let i = 0; i < files.length; i++) {
if (!uploadedFiles.has(files[i].name)) { // 중복 파일 확인
uploadedFiles.add(files[i].name); // Set에 파일 이름 추가
newFiles.push(files[i]); // 처리할 파일 배열에 추가
}
}
console.log('newFiles',newFiles);
if (newFiles.length > 0) {
processFiles(newFiles, tablename, type, inputId); // 중복되지 않은 파일만 처리
}
}
// 파일 업로드 및 처리 함수
function processFiles(files, tablename, item, upfilename) {
if (!files || files.length === 0) {
console.warn("파일이 선택되지 않았습니다.");
return;
}
console.log("processFiles 호출됨"); // 함수 호출 확인
console.log("업로드 파일 수:", files.length); // 파일 개수 확인
showMsgModal(3); // 파일처리중
const form = $('#board_form')[0];
const formData = new FormData(form);
for (const file of files) {
if (!uploadedFiles.has(file.name)) {
formData.append(upfilename + "[]", file);
uploadedFiles.add(file.name); // 중복 방지
console.log("추가된 파일:", file.name);
} else {
console.warn("중복 파일 무시됨:", file.name);
}
}
// 추가 데이터 설정
formData.append("tablename", tablename);
formData.append("item", item);
formData.append("upfilename", upfilename);
formData.append("folderPath", "경동기업/uploads");
formData.append("DBtable", "picuploads");
showMsgModal(2); // 파일저장중
// AJAX 요청을 통해 데이터 가져오기
if (ajaxRequest11 !== null) {
ajaxRequest11.abort();
}
ajaxRequest11 = $.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
url: "/filedrive/fileprocess.php",
type: "POST",
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 () {
displayFile();
hideMsgModal();
}, 1000);
ajaxRequest11 = null;
},
error: function (jqxhr, status, error) {
console.error("업로드 실패:", jqxhr, status, error);
ajaxRequest11 = null;
},
});
}
// 첨부 이미지 업로드 처리
$("#upfileimage").change(function (e) {
if (this.files.length === 0) {
// 파일이 선택되지 않았을 때
console.warn("파일이 선택되지 않았습니다.");
return;
}
const form = $('#board_form')[0];
const data = new FormData(form);
// 추가 데이터 설정
data.append("tablename", $("#tablename").val() );
data.append("item", "image");
data.append("upfilename", "upfileimage"); // upfile 파일 name
data.append("folderPath", "경동기업/uploads");
data.append("DBtable", "picuploads");
showMsgModal(1); // 이미지저장중
// AJAX 요청 (Google Drive API)
$.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
url: "/filedrive/fileprocess.php",
type: "POST",
data: data,
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 () {
displayImage();
hideMsgModal();
}, 1000);
},
error: function (jqxhr, status, error) {
console.error("업로드 실패:", jqxhr, status, error);
},
});
});
});
// 화면에서 저장한 첨부된 파일 불러오기
function displayFile() {
$('#displayFile').show();
const params = $("#timekey").val() ? $("#timekey").val() : $("#num").val();
if (!params) {
console.error("ID 값이 없습니다. 파일을 불러올 수 없습니다.");
alert("ID 값이 유효하지 않습니다. 다시 시도해주세요.");
return;
}
console.log("요청 ID:", params); // 요청 전 ID 확인
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'GET',
data: {
num: params,
tablename: $("#tablename").val(),
item: 'attached',
folderPath: '경동기업/uploads',
},
dataType: 'json',
}).done(function (data) {
console.log("파일 데이터:", data);
$("#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 mb-3'>" +
"<div class='d-flex mb-3 align-items-center justify-content-center'>" +
"<span id='file" + index + "'>" +
"<a href='#' onclick=\"downloadFile('" + fileId + "', '" + realName + "'); return false;\">" +
"<span class='fw-bold text-primary'>" + realName + "</span>" +
"</a>" +
"</span> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + index + "' onclick=\"delFileFn('" + index + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayFile").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}).fail(function (error) {
console.error("파일 불러오기 오류:", error);
Swal.fire({
title: "파일 불러오기 실패",
text: "파일을 불러오는 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
// 기존 파일 불러오기 (Google Drive에서 가져오기)
function displayFileLoad() {
$('#displayFile').show();
var data = <?php echo json_encode($savefilename_arr); ?>;
$("#displayFile").html(''); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, i) {
const realName = fileData.realname || '다운로드 파일';
const link = fileData.link || '#';
const fileId = fileData.fileId || null;
if (!fileId) {
console.error("fileId가 누락되었습니다. index: " + i, fileData);
return;
}
$("#displayFile").append(
"<div class='row mb-3'>" +
"<div class='d-flex mb-3 align-items-center justify-content-center'>" +
"<span id='file" + i + "'>" +
"<a href='#' onclick=\"downloadFile('" + fileId + "', '" + realName + "'); return false;\">" +
"<span class='fw-bold text-primary'>" + realName + "</span>" +
"</a>" +
"</span> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + i + "' onclick=\"delFileFn('" + i + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayFile").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}
// 파일 삭제 처리 함수
function delFileFn(divID, fileId) {
Swal.fire({
title: "파일 삭제 확인",
text: "정말 삭제하시겠습니까?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "삭제",
cancelButtonText: "취소",
reverseButtons: true,
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'DELETE',
data: JSON.stringify({
fileId: fileId,
tablename: $("#tablename").val(),
item: "attached",
folderPath: "경동기업/uploads",
DBtable: "picuploads",
}),
contentType: "application/json",
dataType: 'json',
}).done(function (response) {
if (response.status === 'success') {
console.log("삭제 완료:", response);
$("#file" + divID).remove();
$("#delFile" + divID).remove();
Swal.fire({
title: "삭제 완료",
text: "파일이 성공적으로 삭제되었습니다.",
icon: "success",
confirmButtonText: "확인",
});
} else {
console.log(response.message);
}
}).fail(function (error) {
console.error("삭제 중 오류:", error);
Swal.fire({
title: "삭제 실패",
text: "파일 삭제 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
});
}
// 첨부된 이미지 불러오기
function displayImage() {
$('#displayImage').show();
const params = $("#timekey").val() ? $("#timekey").val() : $("#num").val();
if (!params) {
console.error("ID 값이 없습니다. 파일을 불러올 수 없습니다.");
alert("ID 값이 유효하지 않습니다. 다시 시도해주세요.");
return;
}
console.log("요청 ID:", params); // 요청 전 ID 확인
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'GET',
data: {
num: params,
tablename: $("#tablename").val(),
item: 'image',
folderPath: '경동기업/uploads',
},
dataType: 'json',
}).done(function (data) {
console.log("파일 데이터:", data);
$("#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='col 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=\"delImageFn('" + index + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayImage").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}).fail(function (error) {
console.error("파일 불러오기 오류:", error);
Swal.fire({
title: "파일 불러오기 실패",
text: "파일을 불러오는 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
// 기존 이미지 불러오기 (Google Drive에서 가져오기)
function displayImageLoad() {
$('#displayImage').show();
var data = <?php echo json_encode($saveimagename_arr); ?>;
$("#displayImage").html(''); // 기존 내용 초기화
if (Array.isArray(data) && data.length > 0) {
data.forEach(function (fileData, i) {
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: " + i, fileData);
return;
}
$("#displayImage").append(
"<div class='row mb-3'>" +
"<div class='col d-flex align-items-center justify-content-center'>" +
"<a href='#' onclick=\"popupCenter('" + link + "', 'imagePopup', 800, 600); return false;\">" +
"<img id='image" + i + "' src='" + thumbnail + "' style='width:150px; height:auto;'>" +
"</a> &nbsp;&nbsp;" +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + i + "' onclick=\"delImageFn('" + i + "', '" + fileId + "')\">" +
"<i class='bi bi-trash'></i>" +
"</button>" +
"</div>" +
"</div>"
);
});
} else {
$("#displayImage").append(
"<div class='text-center text-muted'>No files</div>"
);
}
}
// 이미지 삭제 처리 함수
function delImageFn(divID, fileId) {
Swal.fire({
title: "이미지 삭제 확인",
text: "정말 삭제하시겠습니까?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "삭제",
cancelButtonText: "취소",
reverseButtons: true,
}).then((result) => {
if (result.isConfirmed) {
$.ajax({
url: '/filedrive/fileprocess.php',
type: 'DELETE',
data: JSON.stringify({
fileId: fileId,
tablename: $("#tablename").val(),
item: "image",
folderPath: "경동기업/uploads",
DBtable: "picuploads",
}),
contentType: "application/json",
dataType: 'json',
}).done(function (response) {
if (response.status === 'success') {
console.log("삭제 완료:", response);
$("#image" + divID).remove();
$("#delImage" + divID).remove();
Swal.fire({
title: "삭제 완료",
text: "파일이 성공적으로 삭제되었습니다.",
icon: "success",
confirmButtonText: "확인",
});
} else {
console.log(response.message);
}
}).fail(function (error) {
console.error("삭제 중 오류:", error);
Swal.fire({
title: "삭제 실패",
text: "파일 삭제 중 문제가 발생했습니다.",
icon: "error",
confirmButtonText: "확인",
});
});
}
});
}
</script>