在 Web 開發中,檔案上傳幾乎是必備功能。問題在於:檔案一大,使用者就會盯著頁面發呆,不知道究竟傳了多少、還要等多久。這種「黑箱等待」體驗極差。解法是在上傳的同時把進度實時反映出來,讓使用者心裡有數。
本實例的流程:打開上傳頁,點擊「瀏覽」挑選檔案(限制 50MB 以內,超出會給出提示),再點擊「提交」,此時頁面會顯示一條動態增長的進度條與百分比。
實現的關鍵是 Apache Jakarta Commons 下的開源組件 Common-FileUpload。它能完成分段式上傳,也正因如此,我們才有機會在上傳過程中反覆讀取「已經傳了多少」。
Common-FileUpload 的職責是把 multipart/form-data 類型的請求中各種表單域解析出來;它同時依賴另一個組件 Common-IO。兩者的 jar 包都可以從 https://commons.apache.org 下載。
先建立工廠對象,再由工廠生成上傳對象:
DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory);
有了上傳對象,就能調用 parseRequest() 取出全部表單項:
public List parseRequest(HttpServletRequest request) throws FileUploadException
在 Common-FileUpload 的世界裡,檔案域和普通表單域一律被視為 FileItem。判斷方法很直接:調用 isFormField(),返回 true 說明是普通表單域,否則就是檔案域。上傳時可用 getName() 取檔名、getSize() 取檔案大小。
新建 request.js,把 Ajax 請求方法寫在裡面,供頁面引入。
頁面需要三樣東西:承載檔案資訊的表單、展示進度條的 div、展示百分比的 span。
<form enctype="multipart/form-data" method="post" action="UpLoad?action=uploadFile">
請選擇上傳的文件:<input name="file" type="file" size="34">
注:檔案大小請控制在 50M 以內。
<div id="progressBar" class="prog_border" align="left"> <img src="images/progressBar.gif" width="0" height="13" id="imgProgress"></div> <span id="progressPercent" style="width:40px;display:none">0%</span> <input name="Submit" type="button" value="提交" onClick="deal(this.form)"> <input name="Reset" type="reset" class="btn_grey" value="重置"></td> </form>
注意表單必須設置 enctype="multipart/form-data",否則後端根本收不到檔案。
核心方法 uploadFile() 做了四件事:解析請求、逐段讀取位元組寫入目標檔案、同步計算百分比、把百分比即時存進 Session 供前端輪詢。
public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=GBK"); request.setCharacterEncoding("GBK"); HttpSession session=request.getSession(); session.setAttribute("progressBar",0); //定義指定上傳進度的Session變量 String error = ""; int maxSize=50*1024*1024; //單個上傳文件大小的上限 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List items = upload.parseRequest(request); // 解析上傳請求 Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (!item.isFormField()) { // 判斷是否為文件域 if (item.getName() != null && !item.getName().equals("")) { long upFileSize=item.getSize(); String fileName=item.getName(); if(upFileSize>maxSize){ error="您上傳的文件太大,請選擇不超過50M的文件"; break; } File tempFile = new File(fileName); String uploadPath = this.getServletContext().getRealPath("/upload"); File file = new File(uploadPath,tempFile.getName()); InputStream is=item.getInputStream(); int buffer=1024; int length=0; byte[] b=new byte[buffer]; double percent=0; FileOutputStream fos=new FileOutputStream(file); while((length=is.read(b))!=-1){ percent+=length/(double)upFileSize*100D; //計算上傳文件的百分比 fos.write(b,0,length); session.setAttribute("progressBar",Math.round(percent)); } fos.close(); Thread.sleep(1000); //線程休眠1秒 } else { error="沒有選擇上傳文件!"; } } } } catch (Exception e) { e.printStackTrace(); error = "上傳文件出現錯誤:" + e.getMessage(); } if (!"".equals(error)) { request.setAttribute("error", error); request.getRequestDispatcher("error.jsp").forward(request, response); }else { request.setAttribute("result", "文件上傳成功!"); request.getRequestDispatcher("upFile_deal.jsp").forward(request, response); } }
這裡有個容易忽略的細節:上傳與「查詢進度」是兩個獨立的請求。前者忙著寫檔案,後者只負責讀 Session 中的數字,兩者互不阻塞——這正是進度條能動起來的原因。
在 index.jsp 中引入 request.js,並編寫獲取進度的請求與回調:
<script language="javascript" src="js/request.js"></script> <script language="javascript"> var request = false; function getProgress(){ var url="showProgress.jsp"; var param ="nocache="+new Date().getTime(); //每次請求URL參數都不同 ,避免上傳時進度條不動 request=httpRequest("post",url,true,callbackFunc,param); } //Ajax回調函數 function callbackFunc(){ if( request.readyState==4 ){ if( request.status == 200 ){ var h = request.responseText; h=h.replace(/\s/g,""); //去除字符串中的Unicode空白符 document.getElementById("progressPercent").style.display=""; progressPercent.innerHTML=h+"%"; document.getElementById("progressBar").style.display="block"; document.getElementById("imgProgress").width=h*(235/100); //按比例設定進度條寬度 } } } </script>
用 EL 表達式把 Session 中的進度值輸出成純文本:
<%@page contentType="text/html" pageEncoding="GBK"%> ${progressBar}
提交表單的同時啟動一個計時器,每 500 毫秒拉一次最新進度:
function deal(form){ form.submit(); //提交表單 timer=window.setInterval("getProgress()",500); //每隔500毫秒獲取一次上傳進度 }
整體思路可以概括為一句話:真正的上傳交給表單去做,進度條則靠一條独立的 Ajax 通道去「取貨」。兩條線並行,使用者就看到了流暢的百分比增長。