我們要打造的是一個具備 Ajax 能力的組件:它不只把檔案上傳到伺服器,還能「即時」監看整個上傳過程。
public class ProgressMonitorFileItem extends DiskFileItem {
private ProgressObserver observer;
private long passedInFileSize;
private boolean isFormField;
@Override
public OutputStream getOutputStream() throws IOException {
OutputStream baseOutputStream = super.getOutputStream();
if (isFormField == false) {
return new BytesCountingOutputStream(baseOutputStream);
} else {
return baseOutputStream;
}
}
private class BytesCountingOutputStream extends OutputStream {
private long previousProgressUpdate;
private OutputStream base;
public BytesCountingOutputStream(OutputStream ous) { base = ous; }
private void fireProgressEvent(int b) {
bytesRead += b;
double progress = (((double) (bytesRead)) / passedInFileSize);
progress *= 100.0;
observer.setProgress(progress);
}
}
}
ProgressMonitorFileItem 把 DiskFileItem 預設的 OutputStream 包進 BytesCountingOutputStream,於是每寫入一定數量的位元組後,就能更新相關的 ProgressObserver。
這個組件負責產生 HTML 檔案上傳標籤、顯示監視上傳的進度條,以及在檔案上傳成功後要呈現的內容。用 JavaServer Faces 實作的一大優點是複雜度幾乎都被藏了起來:開發者只要把標籤加進 JSP,其餘的 Ajax 細節與進度條監控都交給組件。以下 JSP 片段示範如何把上傳組件加入頁面:
<comp:fileUpload
value="#{uploadPageBean.uploadedFile}"
uploadIcon="images/upload.png"
styleClass="progressBarDiv"
progressBarStyleClass="progressBar"
cellStyleClass="progressBarCell"
activeStyleClass="progressBarActiveCell">
<%-- 檔案上傳完成後才會顯示的內容 --%>
<h:panelGrid columns="2" cellpadding="2" cellspacing="0" width="100%">
<f:facet name="header">
<h:outputText styleClass="text" value="檔案上傳成功." />
</f:facet>
<h:panelGroup style="text-align:left;display:block;width:100%;">
<h:commandButton action="#{uploadPageBean.reset}" image="images/reset.png" />
</h:panelGroup>
<h:panelGroup style="text-align:right;display:block;width:100%;">
<h:commandButton action="#{uploadPageBean.nextPage}" image="images/continue.png" />
</h:panelGroup>
</h:panelGrid>
</comp:fileUpload>
value 屬性需要綁定到一個持有 FileItem 的 bean 屬性;只有在檔案被伺服器成功接收後,這段內容才會顯示。
本質上,上傳組件要嘛產生完整的自己,要嘛在收到 Ajax 請求時只產生部分 XML 來更新進度條狀態。為了避免 JavaServer Faces 每次都建出完整的組件樹(那會帶來不必要的負擔),我們還實作了一個 PhaseListener(PagePhaseListener),一旦遇到 Ajax 請求就取消該 faces 請求的其餘處理。標準設定(faces-config.xml 與標籤庫)相當直接,且已隨程式碼附上,這裡不再贅述。
組件與標籤類別的實作相當單純,大量邏輯都集中在產生器中,它負責:
上傳組件由三個階段構成,以下逐一說明。組件在頁面上的可視性(以 CSS 控制)由 Ajax JavaScript 負責切換。

圖 5. 選擇檔案上傳
第一階段要產生 HTML 的 file 輸入標籤,以及點擊 Upload 時的對應程式碼。使用者按下按鈕後,表單會透過一個隱藏 IFRAME 提交(避免頁面被鎖住),並初始化第二階段:
// 檔案上傳組件
writer.startElement("input", component);
writer.writeAttribute("type", "file", null);
writer.writeAttribute("name", component.getClientId(context), "id");
writer.writeAttribute("id", component.getClientId(context), "id");
if (input.getValue() != null) {
FileItem fileData = (FileItem) input.getValue();
writer.writeAttribute("value", fileData.getName(), fileData.getName());
}
writer.endElement("input");
String iconURL = input.getUploadIcon();
writer.startElement("div", component);
writer.writeAttribute("style", "display:block;width:100%;text-align:center;", "style");
writer.startElement("img", component);
writer.writeAttribute("src", iconURL, "src");
writer.writeAttribute("type", "image", "type");
writer.writeAttribute("style", "cursor:hand;cursor:pointer;", "style");
UIForm form = FacesUtils.getForm(context, component);
if (form != null) {
String getFormJS = "document.getElementById('" + form.getClientId(context) + "')";
String JSFriendlyClientID = input.getClientId(context).replace(":", "_");
// 表單編碼改為 multipart,並透過 IFRAME 提交;
// 500 毫秒後啟動第二階段
writer.writeAttribute("onclick",
getFormJS + ".encoding='multipart/form-data';" +
getFormJS + ".target='" + iframeName + "';" +
getFormJS + ".submit();" +
getFormJS + ".encoding='application/x-www-form-urlencoded';" +
getFormJS + ".target='_self';" +
"setTimeout('refreshProgress" + JSFriendlyClientID + "();', 500);", null);
}
writer.endElement("img");
// 建立提交用的隱藏 IFRAME
writer.startElement("iframe", component);
writer.writeAttribute("id", iframeName, null);
writer.writeAttribute("name", iframeName, null);
writer.writeAttribute("style", "display:none;", null);
writer.endElement("iframe");
writer.endElement("div");
writer.endElement("div"); // 階段 1 結束

圖 6. 上傳檔案到伺服器
第二階段顯示目前百分比的進度條與標籤。進度條實作為一個包著 100 個 span 的 div,這些 span 會由 Ajax JavaScript 依伺服器回應逐一設定樣式:
writer.startElement("div", component);
writer.writeAttribute("id", input.getClientId(context) + "_stage2", "id");
writer.writeAttribute("style", "display:none", "style");
String progressBarID = component.getClientId(context) + "_progressBar";
String progressBarLabelID = component.getClientId(context) + "_progressBarLabel";
writer.startElement("div", component);
writer.writeAttribute("id", progressBarID, "id");
String progressBarStyleClass = input.getProgressBarStyleClass();
if (progressBarStyleClass != null)
writer.writeAttribute("class", progressBarStyleClass, "class");
for (int i = 0; i < 100; i++) {
writer.write("<span> </span>");
}
writer.endElement("div");
writer.startElement("div", component);
writer.writeAttribute("id", progressBarLabelID, "id");
writer.endElement("div");
writer.endElement("div"); // 階段 2 結束

圖 7. 上傳完成
最後,檔案成功上傳後需要顯示的內容在 encodeChildren 中產生:
public void encodeChildren(FacesContext context, UIComponent component)
throws IOException {
ResponseWriter writer = context.getResponseWriter();
UIFileUpload input = (UIFileUpload) component;
writer.startElement("div", component);
writer.writeAttribute("id", input.getClientId(context) + "_stage3", "id");
if (input.getValue() == null) {
writer.writeAttribute("style", "display:none;", null);
} else {
writer.writeAttribute("style", "display:block", null);
}
List<UIComponent> children = input.getChildren();
for (UIComponent child : children) {
FacesUtils.encodeRecursive(context, child);
}
writer.endElement("div"); // 階段 3 結束
}