上傳大檔案時,如果畫面上能看見進度,使用者體驗會好很多。實作思路是:伺服器端用監聽器即時追蹤已讀位元組數並寫入 session,用戶端則定時以異步請求向伺服器查詢進度,再將結果渲染成視覺效果。

public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 取出監聽器寫入 session 的進度
String progress = (String) req.getSession().getAttribute("progress");
resp.getWriter().print(progress);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 掛上監聽器
upload.setProgressListener(new MyProgressListener(req));
try {
List<FileItem> list = upload.parseRequest(req);
for (FileItem fileItem : list) {
if (fileItem.isFormField()) {
// 普通表單欄位
} else {
String path = req.getRealPath("uploads");
String fileName = fileItem.getName();
File file = new File(path, fileName);
fileItem.write(file);
System.out.println("成功上傳檔案:" + fileName);
}
}
} catch (Exception e) {
System.out.println("檔案上傳發生錯誤!");
e.printStackTrace();
}
}
}同一個 Servlet 同時肩負兩個角色:POST 負責接收檔案,GET 則作為進度查詢端點。這是讓進度條能運作的關鍵設計。
public class MyProgressListener implements ProgressListener {
private HttpSession session;
public MyProgressListener(HttpServletRequest request) {
session = request.getSession();
}
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
double readM = pBytesRead / 1024.0 / 1024.0;
double totalM = pContentLength / 1024.0 / 1024.0;
double percent = readM / totalM;
String readf = dataFormat(pBytesRead);
String totalf = dataFormat(pContentLength);
NumberFormat format = NumberFormat.getPercentInstance();
String progress = format.format(percent);
session.setAttribute("progress", progress);
}
/**
* 將位元組數格式化為易讀單位
*/
public String dataFormat(double data) {
String formdata;
if (data >= 1024 * 1024) {
formdata = Double.toString(data / 1024 / 1024) + "M";
} else if (data >= 1024) {
formdata = Double.toString(data / 1024) + "KB";
} else {
formdata = Double.toString(data) + "byte";
}
return formdata.substring(0, formdata.indexOf(".") + 2);
}
}update() 會在上傳過程中不斷被呼叫,把百分比寫進 session;前端只要輪詢讀取,就能拿到最新狀態。
<html>
<head>
<title>帶進度條的檔案上傳效果</title>
<style type="text/css">
#progressBar { width: 300px; height: 20px; border: 1px #EEE solid; }
#progress { width: 0%; height: 20px; background-color: lime; }
</style>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
function upload() {
$("#f1").submit();
var pro = setInterval(function () {
$.get("UploadServlet", "", function (data) {
$("#proInfo").text("上傳進度:" + data);
$("#progress").width(data);
if (data == '100%') {
clearInterval(pro);
}
});
}, 200);
}
</script>
</head>
<body>
<iframe name="aa" style="display: none;"></iframe>
<h2>帶進度條的檔案上傳效果</h2>
<form target="aa" id="f1" action="UploadServlet" method="post" enctype="multipart/form-data">
檔案:<input name="file" type="file">
<input type="button" value="上傳" onclick="upload();">
<div id="progressBar"><div id="progress"></div></div>
<span id="proInfo">上傳進度:0%</span>
</form>
</body>
</html>兩個關鍵細節:表單的 target 指向一個隱藏的 iframe,這樣上傳完成後頁面不會跳轉;setInterval 每 200 毫秒輪詢一次進度,收到 100% 就停止計時器。少了這兩點,進度條要嘛把頁面帶走,要嘛永遠不會停。