JavaScript - Drop & Drap File Upload

JavaScript - Drop & Drap File Upload

網路上滿難找到很簡單的程式說明,

https://www.sitepoint.com/html5-file-drag-and-drop/

這篇文章算是我看到最簡單,上面範例,實際複製後,再貼到自己的程式碼裡,

也實際操作,也成功撰寫完成。

只知道需要在HTML5的環境下,

而要使用多選檔案功能需要加上multiple

<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />

而在一開始要先確認是否可使用Drop Drap

		// initialize
		function Init() {

			var fileselect = $id("fileselect"),
				filedrag = $id("filedrag"),
				submitbutton = $id("submitbutton");

			// file select
			fileselect.addEventListener("change", FileSelectHandler, false);

			// is XHR2 available?
			var xhr = new XMLHttpRequest();
			if (xhr.upload) {
			
				// file drop
				filedrag.addEventListener("dragover", FileDragHover, false);
				filedrag.addEventListener("dragleave", FileDragHover, false);
				filedrag.addEventListener("drop", FileSelectHandler, false);
				filedrag.style.display = "block";
				
				// remove submit button
				submitbutton.style.display = "none";
			}
		}		
		
		if (window.File && window.FileList && window.FileReader) {
			Init();
		}

在初始化,設定註冊change事件、dragover事件dragleave事件、drop事件監聽

當選擇了圖片及滑過,做一些事件動作

		// file drag hover
		function FileDragHover(e) {
			e.stopPropagation();
			e.preventDefault();
			e.target.className = (e.type == "dragover" ? "hover" : "");
		}
		
		// file selection
		function FileSelectHandler(e) {

			// cancel event and hover styling
			FileDragHover(e);

			// fetch FileList object
			var files = e.target.files || e.dataTransfer.files;

			// process all File objects
			for (var i = 0, f; f = files[i]; i++) {
				ParseFile(f);
			}
		}

其它的,就是Parse上傳的檔案,輸出,以及一般取得元素的語法。

		function ParseFile(file) {
			Output(
				"<p>File information: <strong>" + file.name +
				"</strong> type: <strong>" + file.type +
				"</strong> size: <strong>" + file.size +
				"</strong> bytes</p>"
			);			
		}
	
	
		// getElementById
		function $id(id) {
			return document.getElementById(id);
		}

		//
		// output information
		function Output(msg) {
			var m = $id("messages");
			m.innerHTML = msg + m.innerHTML;
		}

其它詳細,就參考我貼的文件看就可以了。

其它參考文章

https://css-tricks.com/drag-and-drop-file-uploading/

http://www.codexworld.com/upload-multiple-images-using-jquery-ajax-php/