<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>圖片上傳 | cookie</title>
</head>
<body>
file: <input type="file" id="images" name="image" /><br><br>
desc: <input type="text" id="desc" name="desc" /><br><br>
<input type="button" value="upload" onclick="upload();">
<div class="images"></div>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript" src="js/upload.js"></script>
<script type="text/javascript">
function upload() {
$.ajaxFileUpload({
url: 'upload.htm',
fileElementId: 'images',
dataType: 'json',
data: { desc: $("#desc").val() },
success: function (data) {
var html = $(".images").html();
html += '<img width="100" height="100" src="/HotelManager/upload/' + data.url + '">';
$(".images").html(html);
}
});
return false;
}
</script>
</body>
</html>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String path = request.getServletContext().getRealPath("/upload");
String name = null;
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
System.out.println(item.getFieldName() + ": " + item.getString());
} else {
name = item.getName();
item.write(new File(path, name));
}
}
PrintWriter out = response.getWriter();
out.print("{");
out.print("url:\"" + name + "\"");
out.print("}");
} catch (Exception e) {
e.printStackTrace();
}
}
範例依賴一個名為 ajaxfileupload.js 的第三方套件(網路上很容易找到)。它的原理是動態建立一個隱藏的 <iframe>,讓表單 target 指向它,从而在「看起來像 Ajax」的情況下完成檔案上傳——因為在 $.ajaxFileUpload 這個套件普及的年代,FormData 尚未廣泛支援。
今天完全不需要這個套件。FormData 加上 fetch 幾行就能做到,而且是真的非同步、真的能顯示進度:
<input type="file" id="images">
<input type="text" id="desc" placeholder="描述">
<button id="btn">上傳</button>
<div class="images"></div>
<script>
$('#btn').on('click', function () {
var file = document.getElementById('images').files[0];
if (!file) { alert('請先選擇檔案'); return; }
var fd = new FormData();
fd.append('image', file);
fd.append('desc', $('#desc').val());
fetch('upload', { method: 'POST', body: fd }) // 不要手動設 Content-Type
.then(function (r) { return r.json(); })
.then(function (data) {
// 用 append 而非 html()+=,避免整段重繪與 XSS 風險
var img = document.createElement('img');
img.width = 100; img.height = 100;
img.src = '/HotelManager/upload/' + data.url;
document.querySelector('.images').appendChild(img);
})
.catch(function (err) { alert('上傳失敗:' + err); });
});
</script>
要注意的是:使用 FormData 時千萬不要自己設定 Content-Type,含 boundary 的 multipart 標頭必須由瀏覽器依實際內容產生。
檔名直接用 item.getName() 存檔是危險的。使用者送來的檔名可能包含 ../../ 這類路徑穿越字元,也可能覆蓋伺服器上既有的檔案。請改用伺服器端產生的隨機檔名(例如 GUID 或雜湊值),只保留副檔名。
完全沒有驗證檔案類型與大小。只檢查副檔名或 Content-Type 都可以被偽造,應以實際內容判斷(例如讀取 magic number 或用 ImageIO.read() 嘗試解析)。大小也必須限制,否則容易被打爆。
上傳目錄不該放在 Web 可存取的根目錄下。getRealPath("/upload") 意味著上傳的檔案可以被人直接用網址開啟。若該目錄允許執行腳本,等於把伺服器交給對方。請存到 Web 根目錄之外,或至少關閉該目錄的腳本執行權限。
例外被 printStackTrace() 吞掉,前端只收到空白。請回傳有意義的錯誤狀態碼與 JSON 訊息,前端才能正確提示使用者。
回傳的 JSON 字串是手動拼的。out.print("{"); out.print("url:\"" + name + "\""); 這種寫法一旦檔名含引號就會產生無效 JSON。請用 com.google.gson.Gson 或 Jackson 序列化物件。