본문 바로가기
JAVASCRIPT

[JQuery File Upload] API를 이용한 파일 업로드 테스트

by Hwoarang757 2022. 7. 31.

출처 : GitHub - blueimp/jQuery-File-Upload: File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads. Works with any server-side platform (Google App Engine, PHP, Python, Ruby on Rails, Java, etc.) that supports standard HTML form file uploads.

 

GitHub - blueimp/jQuery-File-Upload: File Upload widget with multiple file selection, drag&drop support, progress bar, validatio

File Upload widget with multiple file selection, drag&drop support, progress bar, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file up...

github.com

 

등록 할 파일을 선택 또는 , Drag And Drop 을 이용하여 파일을 첨부하고 

 

등록 하기 전 파일을 삭제 할 수 있도록 버튼을 생성 하였습니다.

 

파일등록 버튼을 클릭 하였을 때 , 선택한 파일 모두 서버에 업로드 처리 하게 구현 해보았습니다. 

 

내공이 부족 하여 수정할 사항이 많습니다 -_-;;

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1">
<meta name="viewport" name="viewport" content="width=1024">
<meta name="robots" content="index,follow" />
<meta name="subject" content="TestWAS" />
<meta name="keywords" content="TestWAS" />
<meta name="description" content="TestWAS" />
<meta name="copyright" content="copyrights 2022" />
<meta name="classification" content="internet" />
<meta name="distribution" content="global" />
<meta name="language" content="ko" />
<title>파일 업로드 테스트</title>

<style>

	th,td {
		border:1px solid blue;
		padding : 0px
	 }

</style>

</head>



<body>

<button id="btn_attach">찾아보기</button>



<div id="progress">
    <div class="bar" style="width: 0%;"></div>
</div>

<br />
<br />

<div style="width:100%;">
	<div id="fileInfoDiv" style="width:100%;height:100px;background-image:url(/images/bg_dropfile.png);background-repeat:no-repeat;background-position:center;border:1px solid red;display:flex;justify-content:center;"
		ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
	<div style="margin:auto;">여기에 파일을 올리세요.</div>
	</div>
	<table id="tblFileList" style="width:100%;height:300px" >
		<col width="40%" />
		<col width="30%" />
		<col width="30%" />
		<thead>
			<tr>
				<th>파일명</th>
				<th>파일크기</th>
				<th>파일제어</th>
			</tr>
		</thead>
		<tbody>

		</tbody>


	</table>
</div>



<br />
<br />


<button id="btn_upload" style="position:relative">파일등록</button>

<br />


<div id="divFileCtlList">

</div>

</body>


<!--
<input type="file" id="fileUpload" name="fileUpload[]" onchange="ajaxFileUpload();" style="opacity: 0; filter: alpha(opacity = 0)" value="" />
<input id="fileupload" type="file" name="files[]"  multiple style="width:50%"/>
 -->



<script src="/scripts/jquery-3.6.0/jquery.js"></script>
<script src="/scripts/jquery-file-upload/js/vendor/jquery.ui.widget.js"></script>
<script src="/scripts/jquery-file-upload/js/jquery.iframe-transport.js"></script>
<script src="/scripts/jquery-file-upload/js/jquery.fileupload.js"></script>

<script type="text/javascript">

var fileIdx = 0;

	$(document).ready(function() {

		$("#btn_attach").on("click",function() {
			fileAttach();
		});


		$("#btn_test").on("click",function() {
			test();
		});

		$("#btn_upload").on("click",function() {

			// 파일 리스트의 삭제 버튼을 숨긴다.
			$("#tblFileList tbody tr").each(function() {
				$(this).children("td:eq(2)").find("button").hide();
			});

			$("#divFileCtlList").children().each(function() {
				for(let i = 0 ; i <= fileIdx ; i++) {
					if($("#btnUpload" + i.toString()) !== undefined) {
						$("#btnUpload" + i.toString()).click();
					}
				}
			});
		});

	});


	function fileAttach() {
		$("<input type=\"file\" id=\"fileUpload" + fileIdx + "\" name=\"fileUpload" + fileIdx + "\" style=\"opacity: 0; filter: alpha(opacity = 0)\"/>").appendTo("#divFileCtlList");


		$("#fileUpload" + fileIdx.toString()).fileupload({
			url : "/UploadFile",
			add : function(e,data) {
				$("<tr>"
					+ "<td id=\"tdfileUpload" + fileIdx.toString() + "\">" + data.files[0].name + "</td>"
					+ "<td>" + data.files[0].size + "</td>"
					+ "<td style='text-align:center'><span id=\"spPrg" + fileIdx.toString() + "\">0%</span>&nbsp;" + "<button onclick='deleteFileRow(\"" + "fileUpload" + fileIdx.toString() + "\")'>삭제</button>"
				    + "</tr>"
				).appendTo("#tblFileList").find("tbody");

				data.context = $("<button id=\"btnUpload" + fileIdx.toString() + "\" style=\"opacity: 0; filter: alpha(opacity = 0)\"></button>").text("upload")
							   .appendTo("#divFileCtlList")
							   .click(function() {
								  data.submit();
							   });
				fileIdx++;
			},
			progress: function(e, data) {

				    var progress = parseInt((data.loaded / data.total) * 100, 10);
					$("#" + $(data.context).attr("id").replace(/btnUpload/gi,"spPrg") ).text(progress.toString() + "%");

			},
	        done: function (e, data) {
	            console.log('Upload finished.');
	        }
		});

		$("#fileUpload" + fileIdx.toString()).click();

	}



	function deleteFileRow(fileUploadId) {

		// FileUpload 객체를 삭제 시킨다.
		$("#" + fileUploadId).remove();

		// DataRow를 삭제 처리 한다.
		$("#td" + fileUploadId).parent().remove();

		// btnUpload 버튼을 삭제 한다.
		$("#" + fileUploadId.replace(/fileUpload/gi,"btnUpload") ).remove();

	}



	function DropZoneFile(e) {
		console.log("drop");
		$("<input type=\"file\" id=\"fileUpload" + fileIdx + "\" name=\"fileUpload" + fileIdx.toString() + "\"  style=\"opacity: 0; filter: alpha(opacity = 0)\"  />").appendTo("#divFileCtlList");

		$("#fileUpload" + fileIdx.toString()).fileupload({
			url : "/UploadFile",
			add : function(e,data) {

					console.log("#tdfileUpload" + fileIdx.toString() + ".length=" +  $("#tdfileUpload" + fileIdx.toString()).length );
					console.log("data.files.length=" +  data.files.length );

					let exists = false;
					$("#tblFileList tbody tr").each(function() {
						if($(this).find("td:eq(0)").text() === data.files[0].name)
							exists = true;

						if(exists) return;
					});

					if(exists) return false;

					$("<tr>"
						+ "<td id=\"tdfileUpload" + fileIdx.toString() + "\">" + data.files[0].name + "</td>"
						+ "<td>" + data.files[0].size + "</td>"
						+ "<td style='text-align:center'><span id=\"spPrg" + fileIdx.toString() + "\">0%</span>&nbsp;" + "<button onclick='deleteFileRow(\"" + "fileUpload" + fileIdx.toString() + "\")'>삭제</button>"
					    + "</tr>"
					).appendTo("#tblFileList").find("tbody");

					data.context = $("<button id=\"btnUpload" + fileIdx.toString() + "\" style=\"opacity: 0; filter: alpha(opacity = 0)\"></button>").text("upload")
								   .appendTo("#divFileCtlList")
								   .click(function() {
									  data.submit();
								   });
					fileIdx++;

			},
			progress: function(e, data) {

				    var progress = parseInt((data.loaded / data.total) * 100, 10);
					$("#" + $(data.context).attr("id").replace(/btnUpload/gi,"spPrg") ).text(progress.toString() + "%");

			},
	        done: function (e, data) {
	            console.log('Upload finished.');
	        }
		});

		//$("#fileUpload" + fileIdx.toString()).fileupload("add" , {files : e.getAsFile});

	}

	function dropHandler(event) {
		console.log('File(s) dropped');

		// Prevent default behavior (Prevent file from being opened)
	    event.preventDefault();
		console.log('DropZoneFile(event);');
		DropZoneFile(event);
	}

	function dragOverHandler(event) {
		console.log("File(s) in drop zone");

	    event.preventDefault();


	}

</script>

</html>