티스토리 뷰
며칠을 시름했을까?
긴 터널을 빠져나온 기분이네요~
이 코드를 완성하고 한결 마음이 편안해 졌습니다.
이미지, 첨부파일에 대한 고민을 조금은 덜은 것 같군요~
<div class="d-flex mt-1 mb-1 justify-content-center">
<label for="upfileimage" class="input-group-text btn btn-outline-dark btn-sm "> 사진 첨부 </label>
<input id="upfileimage" name="upfileimage[]" type="file" onchange="this.value" multiple accept=".gif, .jpg, .png" style="display:none">
</div>
<div id ="displayImage" style="display:none;"> </div>
<div class="d-flex mt-3 mb-1 justify-content-center">
<label for="upfile" class="input-group-text btn btn-outline-primary btn-sm"> 파일(10M 이하) pdf파일 첨부 </label>
<input id="upfile" name="upfile[]" type="file" onchange="this.value" multiple style="display:none" >
</div>
<div id ="displayFile" style="display:none;"> </div>
</div>
<script>
$(document).ready(function () {
displayFileLoad(); // 기존파일 업로드 보이기
displayImageLoad(); // 기존이미지 업로드 보이기
// 첨부파일 업로드 처리
$("#upfile").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", "attached");
data.append("upfilename", "upfile"); // upfile 파일 name
data.append("folderPath", "미래기업/uploads");
data.append("DBtable", "picuploads");
showMsgModal(2); // 파일저장중
// AJAX 요청 (Google Drive API)
$.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
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 () {
displayFile();
hideMsgModal();
}, 1000);
},
error: function (jqxhr, status, error) {
console.error("업로드 실패:", jqxhr, status, error);
},
});
});
// 첨부 이미지 업로드 처리
$("#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,
cache: false,
timeout: 600000,
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 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> " +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + index + "' onclick=\"delFileFn('" + index + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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=\"popupCenter('" + link + "', 'filePopup', 800, 600); return false;\">" + realName + "</a>" +
"</span> " +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + i + "' onclick=\"delFileFn('" + i + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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> " +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + index + "' onclick=\"delImageFn('" + index + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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> " +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + i + "' onclick=\"delImageFn('" + i + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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>
</body>
</html>
이 컨셉으로 실행하면 아래의 화면과 같이 활용가능합니다.
코드를 담는 것으로 다시 정리하면,
html 부분
<div class="d-flex mt-1 mb-1 justify-content-center">
<label for="upfileimage" class="input-group-text btn btn-outline-dark btn-sm "> 사진 첨부 </label>
<input id="upfileimage" name="upfileimage[]" type="file" onchange="this.value" multiple accept=".gif, .jpg, .png" style="display:none">
</div>
<div id ="displayImage" style="display:none;"> </div>
<div class="d-flex mt-3 mb-1 justify-content-center">
<label for="upfile" class="input-group-text btn btn-outline-primary btn-sm"> 파일(10M 이하) pdf파일 첨부 </label>
<input id="upfile" name="upfile[]" type="file" onchange="this.value" multiple style="display:none" >
</div>
<div id ="displayFile" style="display:none;"> </div>
자바스크립트 부분
<script>
$(document).ready(function () {
displayFileLoad(); // 기존파일 업로드 보이기
displayImageLoad(); // 기존이미지 업로드 보이기
// 첨부파일 업로드 처리
$("#upfile").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", "attached");
data.append("upfilename", "upfile"); // upfile 파일 name
data.append("folderPath", "미래기업/uploads");
data.append("DBtable", "picuploads");
showMsgModal(2); // 파일저장중
// AJAX 요청 (Google Drive API)
$.ajax({
enctype: 'multipart/form-data',
processData: false,
contentType: false,
cache: false,
timeout: 600000,
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 () {
displayFile();
hideMsgModal();
}, 1000);
},
error: function (jqxhr, status, error) {
console.error("업로드 실패:", jqxhr, status, error);
},
});
});
// 첨부 이미지 업로드 처리
$("#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,
cache: false,
timeout: 600000,
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 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> " +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + index + "' onclick=\"delFileFn('" + index + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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=\"popupCenter('" + link + "', 'filePopup', 800, 600); return false;\">" + realName + "</a>" +
"</span> " +
"<button type='button' class='btn btn-danger btn-sm' id='delFile" + i + "' onclick=\"delFileFn('" + i + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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> " +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + index + "' onclick=\"delImageFn('" + index + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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> " +
"<button type='button' class='btn btn-danger btn-sm' id='delImage" + i + "' onclick=\"delImageFn('" + i + "', '" + fileId + "')\">" +
"<ion-icon name='trash-outline'></ion-icon>" +
"</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>
</body>
</html>
'IT tech Coding > javascript' 카테고리의 다른 글
[자바스크립트+html] Font Awesome 아이콘과 Popper.js를 조합하여 깔끔한 UI를 구현 (알람 내용 확인해 주세요) 구현 (0) | 2024.11.30 |
---|---|
Chrome is moving towards a new experience that allows users to choose to browse without third-party cookies. 의미는 무엇인가? (0) | 2024.11.27 |
웹개발시 자주 사용하는 파일업로드시, 저장시 등 활용모달 (0) | 2024.11.19 |
자바스크립트로 현재날짜 넣는 간단 방법 (0) | 2024.10.22 |
자바스크립트로 견적금액 소계, 합계 만들어보자구요~ (0) | 2024.10.17 |
- Total
- Today
- Yesterday
- 오토핫키가이드
- 1. #웹개발 2. #로트번호 3. #성적서보기 4. #ajax 5. #jquery 6. #php 7. #프론트엔드 8. #백엔드 9. #부트스트랩 10. #웹기능구현
- General error: 2031
- isset을 적용해야 하는 이유
- #웹개발
- 코딩튜토리얼
- #트리구조
- #카테고리트리
- 효율적코딩방법
- ajax오류메시지
- 캐드자동작도
- 도면자동생성
- 웹제작강의안2주차
- 엑셀입력보호
- 티스토리챌린지
- #php에러해결 #php경고메시지 #nonwellformednumeric #php초보자팁 #웹개발에러 #프로그래밍디버깅 #php정규식 #코드디버깅팁 #웹개발문제해결 #php숫자형변환
- 오블완
- Bootstrap 5
- coalesce는 한국어로 "코얼레스크" 또는 "코얼리스"
- #계층형데이터
- json파일형태보기
- #데이터무결성
- 엑셀셀보호
- json파일편하게보는법
- 구글드라이브API
- 엑셀보호
- #데이터베이스설계
- #동적ui
- #tuigrid #자바스크립트그리드 #행삽입 #행삭제 #웹개발팁 #프론트엔드개발 #javascriptgrid #데이터테이블 #ui개선 #그리드커스터마이징
- #textarea #자동높이조절 #ux개선 #웹개발 #프론트엔드 #자바스크립트 #html팁 #웹디자인 #uiux #코딩팁
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |