一次只能選一個檔案的 <input type="file">,遇到要上傳整個目錄時就很折磨人。這篇文章示範一種在舊式(IE + ActiveX)環境下的變通做法:由 JavaScript 遞迴掃描指定目錄下的所有檔案,再把清單逐筆送出。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>測試檔案上傳</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(function(){
// ShowFolderFileList("D:\\CodeNet\\web\\Images\\shopTemplets");
});
// 遞迴列出目錄下的所有檔案
function ShowFolderFileList(FilePath){
var fso, f, fc, sf;
fso = new ActiveXObject("Scripting.FileSystemObject");
try{
f = fso.GetFolder(FilePath);
} catch(err){
alert("檔案路徑錯誤或不存在!!");
return false;
}
// 列出當前目錄的所有檔案
fc = new Enumerator(f.files);
for(; !fc.atEnd(); fc.moveNext()){
var fileName = fc.item().Name;
$('<div filePath="' + FilePath + fileName + '" uploadState="wait">'
+ FilePath + fileName + '</div>').appendTo('#showArea');
}
// 遞迴讀取子目錄
sf = new Enumerator(f.SubFolders);
for(; !sf.atEnd(); sf.moveNext()){
var folderName = sf.item().Name;
ShowFolderFileList(FilePath + folderName + "/");
}
}
function startUpload(){
var s = $('#uploaddir').val().replace( /\\/gi, '/' );
if(s.substring(s.length - 1, s.length) != '/'){ s += '/'; }
ShowFolderFileList(s);
uploadFile();
}
// 逐筆上傳
function uploadFile(){
if($('#showArea div[uploadState=wait]').length > 0){
var thisNode = $('#showArea div[uploadState=wait]').eq(0);
var WshShell = new ActiveXObject("WScript.Shell");
$('#fileupload').focus();
WshShell.SendKeys($(thisNode).attr('filePath')); // 路徑不能含中文
uploadForm.submit();
$('#fileupload').focus();
$('#fileupload').get(0).createTextRange().select();
WshShell.SendKeys('{del}');
var dotStr = '.';
$('<span></span>').appendTo(thisNode).css('color', 'green');
var uploadState = setInterval(function(){
if($(thisNode).attr('uploadState') == 'ok'){
clearInterval(uploadState);
$(thisNode).find('span').css('color', 'red').text('(完成)');
uploadFile(); // 接著處理下一筆
} else {
dotStr = (dotStr.length > 15) ? '.' : dotStr + '.';
$(thisNode).find('span').text('(上傳中' + dotStr + ')');
}
}, 1000);
}
}
// 在 iframe 回傳頁面中呼叫,即可實現循環上傳,否則會形成死循環
function uploadFinish(){
$('#showArea div[uploadState=wait]').eq(0).attr('uploadState', 'ok');
}
</script>
<style type="text/css">
body, td, th { font-family: "微軟雅黑", Tahoma, Helvetica, Arial, sans-serif; }
</style>
</head>
<body>
<form action="/a.html" method="post" name="loginForm" style="margin:0; padding:0;">
<input name="uploaddir" id="uploaddir" type="text" value="D:\a" style="width:800px;" />
<input type="button" value="開始" id="startIt" name="startIt" onclick="javascript:startUpload();" />
</form>
<form action="/index/upload" method="post" name="uploadForm"
enctype="multipart/form-data" target="hidden_frame">
<input type="file" name="fileupload" id="fileupload" />
<iframe name="hidden_frame" id="hidden_frame" style="display:none"></iframe>
</form>
<div id="showArea"></div>
</body>
</html>
ShowFolderFileList() 用 Scripting.FileSystemObject 打開指定路徑,先列出當前目錄的檔案,再對每個子目錄遞迴呼叫自己,最後把每一筆都渲染成一個帶 filePath 與 uploadState="wait" 的 div。uploadFile() 永遠只挑第一個狀態為 wait 的項目,透過 WScript.Shell.SendKeys 把完整路徑「打」進 file input,然後提交表單。setInterval 每秒檢查狀態,同時讓「上傳中....」的點數持續變動作為動畫。uploadFinish(),把目前這筆標記為 ok,輪詢偵測到後就接著跑下一筆。把表單的 target 指向一個隱藏 iframe,是為了不上頁跳轉就能接收伺服器回應——這是 Ajax 普及之前的標準手法。而「由回傳頁面主動呼叫父頁函式」則是完成通知的來源,否則輪詢永遠等不到狀態變化,就成了死循環。
但必須誠實說明:這套做法的限制很多,而且幾乎全是硬傷。
ActiveXObject,只在舊版 IE 且安全性設定允許時可用。SendKeys 模擬鍵盤輸入檔案路徑,極不可靠:使用者其間碰一下鍵盤就亂了,而且註解也明講「路徑不能含中文」。今天的正解是 HTML5 的 <input type="file" webkitdirectory>,或用 File / Directory API 配合 FormData 一次送出多檔,進度則用 XMLHttpRequest.upload.onprogress 追蹤。這篇文章的價值在於示範「遞迴掃描 + 佇列序列化上傳 + iframe 完成通知」這套思路——即使換成現代 API,整體骨架其實一模一樣。