在傳統的表單上傳之外,為什麼愈來愈多專案選擇 Uploadify?因為它把許多實務上很麻煩的細節都包好了:前端就能先擋掉超大的檔案、限制副檔名、一次挑多個檔案、即時顯示上傳進度,整體使用體驗與瀏覽器相容性都相當不錯。

本文的做法是把 DWZ 框架中整合過的 Uploadify 功能抽取出來,讓它可以獨立運作,不一定要掛在 DWZ 裡才能跑。為了方便驗證,這裡直接用靜態頁面來測試。

下面這份 HTML 同時示範了兩種用法:第一個檔案欄位是「選好就自動上傳」的單檔模式,第二個則是「先排隊、再一次送出」的多檔模式,並搭配自訂的佇列容器與上傳/取消按鈕。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MyHtml.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link href="resources/dwz/uploadify/css/uploadify.css" rel="stylesheet" type="text/css" media="screen" />
<script src="resources/dwz/js/jquery-1.7.2.js" type="text/javascript"></script>
<script src="resources/dwz/uploadify/scripts/jquery.uploadify.js" type="text/javascript"></script>
<script src="resources/dwz/uploadify/scripts/errorCode.js" type="text/javascript"></script>
<style type="text/css" media="screen">
.my-uploadify-button { background: none; border: none; text-shadow: none; border-radius: 0; }
.uploadify:hover .my-uploadify-button { background: none; border: none; }
.fileQueue { width: 400px; height: 150px; overflow: auto; border: 1px solid #E5E5E5; margin-bottom: 10px; }
</style>
<script type="text/javascript">
$(function(){
$('#testFileInput').uploadify({
swf: 'resources/dwz/uploadify/scripts/uploadify.swf',
uploader: 'servlet/uploadify.do', // 上傳的 URL
formData: { PHPSESSID: 'xxx', ajax: 1 },
buttonText: '請選擇文件',
fileSizeLimit: '200KB', // 限制單檔大小
fileTypeDesc: '*.jpg;*.jpeg;*.gif;*.png;',
fileTypeExts: '*.jpg;*.jpeg;*.gif;*.png;',
auto: true, // 選完即上傳
multi: true,
overrideEvents: ['onDialogClose', 'onUploadError', 'onSelectError'],
onSelectError: uploadify_onSelectError,
onUploadError: uploadify_onUploadError,
onUploadSuccess: uploadify_onUploadSuccess
});
$('#testFileInput2').uploadify({
swf: 'resources/dwz/uploadify/scripts/uploadify.swf',
uploader: 'servlet/uploadify.do',
formData: { PHPSESSID: 'xxx', ajax: 1 },
queueID: 'fileQueue',
buttonImage: 'resources/dwz/uploadify/img/add.jpg',
buttonClass: 'my-uploadify-button',
width: 102,
auto: false, // 手動觸發上傳
fileSizeLimit: '100KB',
fileTypeDesc: '*.jpg;*.jpeg;*.gif;*.png;',
fileTypeExts: '*.jpg;*.jpeg;*.gif;*.png;',
overrideEvents: ['onDialogClose', 'onUploadError', 'onSelectError'],
onSelectError: uploadify_onSelectError,
onUploadError: uploadify_onUploadError,
onUploadSuccess: uploadify_onUploadSuccess
});
});
</script>
</head>
<body>
<!-- 單文件上傳 -->
<input id="testFileInput" type="file" name="image" />
<div class="divider"></div>
<!-- 多文件上傳 -->
<input id="testFileInput2" type="file" name="image2" />
<div id="fileQueue" class="fileQueue"></div>
<input type="image" src="resources/dwz/uploadify/img/upload.jpg" onclick="$('#testFileInput2').uploadify('upload', '*');" />
<input type="image" src="resources/dwz/uploadify/img/cancel.jpg" onclick="$('#testFileInput2').uploadify('cancel', '*');" />
</body>
</html>
前端只是把檔案送出去,真正落地還得靠後端。這裡用 Commons FileUpload 處理 multipart 請求,並先建立一個暫存目錄,避免解析過程直接寫到正式位置。
package uploadFile;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadFile extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
super.service(request, response);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 臨時目錄
String basePath = req.getServletContext().getRealPath("upload");
String tempDir = "temp";
File tempFile = new File(basePath + File.separator + tempDir);
if (!tempFile.exists()) {
tempFile.mkdir();
}
DiskFileItemFactory dfc = new DiskFileItemFactory();
dfc.setSizeThreshold(1 * 1024 * 1024); // 暫存臨界值
dfc.setRepository(tempFile); // 暫存上傳目錄
ServletFileUpload upload = new ServletFileUpload(dfc);
upload.setHeaderEncoding("UTF-8");
upload.setSizeMax(5 * 1024 * 1024); // 單次請求上限 5MB
try {
List fileList = upload.parseRequest(req);
Iterator<FileItem> iterator = fileList.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
String fileName = item.getName();
if (fileName != null) {
File sourceFile = new File(basePath + File.separator + fileName);
item.write(sourceFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
super.doPost(req, resp);
}
}
寫完 Servlet 別忘了登記,否則請求根本進不來。
<servlet> <servlet-name>upLoadify</servlet-name> <servlet-class>uploadFile.UploadFile</servlet-class> </servlet> <servlet-mapping> <servlet-name>upLoadify</servlet-name> <url-pattern>/servlet/uploadify.do</url-pattern> </servlet-mapping>
Uploadify 內建的錯誤訊息是英文的,對使用者不太友善。做法很簡單:覆寫它的錯誤回呼函式,另存成 errorCode.js 放進 resources/dwz/uploadify/scripts,再在頁面中引入即可。
var uploadify_onSelectError = function(file, errorCode, errorMsg) {
var msgText = "上傳失敗\n";
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
msgText += "每次最多上傳 " + this.settings.queueSizeLimit + " 個文件";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
msgText += "文件大小超過限制(" + this.settings.fileSizeLimit + ")";
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
msgText += "文件大小為 0";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
msgText += "文件格式不正確,僅限 " + this.settings.fileTypeExts;
break;
default:
msgText += "錯誤代碼:" + errorCode + "\n" + errorMsg;
}
alert(msgText);
};
var uploadify_onUploadError = function(file, errorCode, errorMsg, errorString) {
// 使用者手動取消不提示
if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED
|| errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
return;
}
var msgText = "上傳失敗\n";
switch (errorCode) {
case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
msgText += "HTTP 錯誤\n" + errorMsg;
break;
case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
msgText += "上傳文件丟失,請重新上傳";
break;
case SWFUpload.UPLOAD_ERROR.IO_ERROR:
msgText += "IO 錯誤";
break;
case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
msgText += "安全性錯誤\n" + errorMsg;
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
msgText += "每次最多上傳 " + this.settings.uploadLimit + " 個";
break;
case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
msgText += errorMsg;
break;
case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
msgText += "找不到指定文件,請重新操作";
break;
case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
msgText += "參數錯誤";
break;
default:
msgText += "文件:" + file.name + "\n錯誤碼:" + errorCode
+ "\n" + errorMsg + "\n" + errorString;
}
alert(msgText);
};
var uploadify_onUploadSuccess = function(file, data, response) {
alert(file.name + "\n\n上傳成功");
};
到這裡整個流程就通了:前端限制條件、Flash 元件負責傳輸、後端 Servlet 落地存檔,錯誤訊息也全部中文化。實際導入正式專案時,建議再補上副檔名白名單與檔名重寫,避免同名覆蓋與不安全的路徑字元。