傳統表單上傳圖片必須整頁刷新,體驗很差。jQuery Form Plugin 提供的 ajaxSubmit() 可以攔下表單送出、改用 AJAX 傳 multipart 資料,做到「選檔 → 上傳 → 存資料」全程不刷新。以下用一個商圈註冊頁當例子,前端 JSP + Bootstrap,後端 SpringMVC。
jquery-1.9.0.js 與 jquery.form.js 兩支即可。
關鍵設定是 enctype="multipart/form-data",少了它檔案不會被送出:
<form class="form-horizontal" method="post"
action="${ctx}/upload/upload.do" id="uploadImgForm"
enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">*商圈名:</label>
<div class="controls">
<input type="text" name="businessName" id="businessName" maxlength="20" />
<input type="hidden" name="userId" id="userId" value="<%=userId%>" />
<div id="businessName_error"></div>
</div>
</div>
<div class="control-group">
<label class="control-label">*商圈 logo:</label>
<div class="controls">
<input type="file" name="file" id="file" />
<div id="file_error"></div>
</div>
</div>
<div class="control-group">
<label class="control-label">*商圈英文名:</label>
<div class="controls">
<input type="text" name="businessEname" id="businessEname" />
<div id="businessEname_error"></div>
</div>
</div>
<div class="form-actions">
<button type="button" id="imgSave" class="btn btn-primary">提交註冊</button>
</div>
</form>
原範例把 userId 放在可見的 text 欄位,這裡改成 type="hidden"。使用者身分識別不該讓使用者看到、更不該讓他改;同時後端仍必須從 session 重新驗證身分,不能信任前端送來的值。
$(document).ready(function() {
// 即時驗證商圈名
$("#businessName").blur(function(){
if ($(this).val() !== "") {
$("#businessName_error").html("<img src='${ctx}/images/success_img.gif' />");
} else {
$("#businessName_error").attr("class","error_div")
.html("<img src='${ctx}/images/error_img2.gif' />商圈名不能為空!");
}
});
// 即時驗證英文名
$("#businessEname").blur(function(){
if ($(this).val() !== "") {
$("#businessEname_error").html("<img src='${ctx}/images/success_img.gif' />");
} else {
$("#businessEname_error").attr("class","error_div")
.html("<img src='${ctx}/images/error_img2.gif' />商圈英文名不能為空!");
}
});
// 送出:先驗檔名格式,再走 ajaxSubmit
$("#imgSave").click(function(){
var ext = '.jpg.jpeg.gif.bmp.png.';
var f = $("#file").val();
if (f === "") {
$("#file_error").attr("class","error_div")
.html("<img src='${ctx}/images/error_img2.gif' />請添加商圈 logo!");
return false;
}
f = f.substr(f.lastIndexOf('.') + 1).toLowerCase();
if (ext.indexOf('.' + f + '.') === -1) {
$("#file_error").attr("class","error_div")
.html("<img src='${ctx}/images/error_img2.gif' />圖片格式不正確!");
return false;
}
var options = {
url: "${ctx}/upload/upload.do",
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == "0") {
// 檔案上傳成功,接著保存表單資料
$.ajax({
type: "post",
url: "${ctx}/business/addBusiness.do",
data: {
businessName: $("#businessName").val(),
businessPic: data.fileName,
businessEname: $("#businessEname").val(),
userId: $("#userId").val()
},
dataType: "json",
success: function (res) {
if (res.status == "0") {
alert("註冊成功!");
} else {
alert("註冊失敗,原因:" + res.message);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
} else {
$("#file_error").attr("class","error_div")
.html("<img src='${ctx}/images/error_img2.gif' />" + data.message);
}
}
};
$('#uploadImgForm').ajaxSubmit(options);
return false; // 阻止表單的預設同步送出
});
});
原範例把第二筆資料用 query string 拼接在 URL 後面,並且對 businessName 重複呼叫了兩次 encodeURI。這裡改用 data 物件傳遞,jQuery 會自動處理 URL 編碼,既乾淨也不會出現重複編碼的問題。用 GET query string 傳中文,是亂碼問題的主要來源之一,能避開就避開。
@Controller
@RequestMapping(value = "/upload")
public class FileUploadController {
private static final Logger logger =
LoggerFactory.getLogger(FileUploadController.class);
@RequestMapping(value = "upload.do", method = RequestMethod.POST)
public void fileUpload(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) request;
CommonsMultipartFile file =
(CommonsMultipartFile) multipartRequest.getFile("file");
String realFileName = file.getOriginalFilename();
if (file.getSize() / 1024 >= 5 * 1024) {
resultMap.put("status", 1);
resultMap.put("message", "圖片不能大於 5M");
} else {
// 存檔名稱加上時間戳,避免同名覆蓋
String newRealFileName = System.currentTimeMillis()
+ realFileName.substring(realFileName.lastIndexOf("."));
String ctxPath = request.getSession().getServletContext()
.getRealPath("//") + "//temp//";
File dirPath = new File(ctxPath);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
File uploadFile = new File(ctxPath + newRealFileName);
FileCopyUtils.copy(file.getBytes(), uploadFile);
resultMap.put("status", 0);
resultMap.put("fileName", newRealFileName);
}
} catch (Exception e) {
resultMap.put("status", 1);
resultMap.put("message", "圖片上傳出錯");
logger.error("圖片上傳出錯", e);
} finally {
// 必須設定編碼,否則回傳的 JSON 中文會亂碼
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write(JSONSerializer.toJSON(resultMap).toString());
out.flush();
}
}
}
原範例用 realFileName.indexOf("."),當檔名含多個點時會切錯位置,這裡改成 lastIndexOf。另外 mkdir() 在需要建立多層目錄時會失敗,改用 mkdirs() 更保險。
副檔名檢查只是第一道防線。前端用 indexOf 比對副檔名,任何人都能改檔名繞過。真正該做的是後端依 Content-Type 與檔案魔術數字(magic number)判斷真實型別,並把存檔目錄設為不可執行,避免上傳 .jsp 造成遠端程式碼執行。
檔案不要存在 web 目錄底下。範例存到 getRealPath() 得到的 temp 目錄,重新部署時這些檔案會全部消失。正式環境應存到外部儲存(磁碟掛載點或物件儲存服務),資料庫只記錄路徑或 key。
檔名一定要重新產生。直接沿用使用者上傳的檔名,會有路徑穿越(../../)與覆蓋攻擊的風險。
記得限制大小與數量。除了單檔 5M 的判斷,也該在 multipart 的設定裡限制整體請求大小,否則會被大量大檔打爆記憶體。