在 FormData 與 Ajax 普及之前,「跨網域上傳檔案且不刷新頁面」幾乎只能靠 form 搭配 iframe。以下記錄一個完整實作,包含前端表單、JavaScript 邏輯與後端 Java 程式,並說明其中幾個容易踩雷的點。
<form id="form" name="form" enctype="multipart/form-data" method="post" target="hidden_frame">
<table style="border:0;width:100%;text-align:middle;">
<tr style="border:0;height:20px;width:100%;">
<td style="border:0;width:75px;height:20px;line-height:20px;">控件標識</td>
<td>
<input id="viewkey" name="viewkey" style="width:200px;" type="text" maxlength="300"
placeholder="控件標識不能超過30個字。" class="easyui-validatebox"
onkeyup="check()" required="true" missingMessage="參數名稱不可為空."/>
</td>
</tr>
<tr>
<td>更新類型</td>
<td><input id="type" name="type" class="easyui-combobox"
valueField="id" textField="text" panelHeight="auto"/></td>
</tr>
<tr>
<td>備註</td>
<td colspan="3">
<textarea id="remark" name="remark" onkeyup="check()"
placeholder="備註不能超過300個字。"
style="width:200px;height:80px;"></textarea>
</td>
</tr>
<tr>
<td>資源文件:</td>
<td>
<input type="file" id="file" name="file"
style="height:25px; width:200px;" onchange="fileChange(this);">
<input type="hidden" name="projectid" id="projectid">
<input type="hidden" name="downimageconfigid" id="downimageconfigid">
<input type="hidden" name="iskeychange" id="iskeychange">
<input type="hidden" name="isnopic" id="isnopic">
<iframe name="hidden_frame" id="hidden_frame" style="display:none"></iframe>
</td>
</tr>
<tr>
<td></td>
<td><div style="color: red; margin-top: 10px;">圖片大小必須小於500K。</div></td>
</tr>
</table>
</form>
最關鍵的一點:form 的 target 必須與 iframe 的 name 完全一致(此處為 hidden_frame),否則送出時仍會跳轉整個頁面。
// 建立對話框
function initDialog() {
$('#imgconf-dialog').dialog({
modal: true,
closable: false,
top: 20,
buttons: [{
id: 'ut_add',
text: '確定',
iconCls: 'icon-ok',
handler: function () {
// 註冊表單事件
$('#form').form({
success: function (data) { // 送出成功後的回呼
if (data === '00') {
jqueryAlert('操作成功');
}
if (data === '03') {
$.messager.alert(global.title, '主鍵為空!', 'warning');
$('#ut_add').linkbutton('enable');
return;
}
if (data === '02') {
$.messager.alert(global.title, '已存在的控件標識!', 'warning');
$('#ut_add').linkbutton('enable');
return;
}
if (data === '01') {
$.messager.alert(global.title, '操作失敗', 'warning');
$('#ut_add').linkbutton('enable');
return;
}
$('#imgconf-dialog').dialog('close');
getDataGridData(); // 重新載入列表
}
});
$('#ut_add').linkbutton('disable');
if (global.operatype == 'add') {
// 【新增】
if ($('#viewkey').val() == null || $('#viewkey').val() == '') {
$.messager.alert(global.title, '您尚未輸入控件標識!', 'warning');
$('#ut_add').linkbutton('enable');
return;
}
if ($('#file').val() == '') {
$.messager.alert(global.title, '您尚未上傳圖片!', 'warning');
$('#ut_add').linkbutton('enable');
return;
}
$('#projectid').val(global.projectid);
$('#form').attr("action", global.web_path + "/grid/imgconf/addimgconf.do");
$("#form").submit();
} else {
// 【編輯】
// 判斷控件標識是否變更
var iskeychange = (selected.viewkey == $('#viewkey').val()) ? 'no' : 'yes';
// 判斷是否有上傳圖片
var isnopic = ($('#file').val() == '') ? 'yes' : 'no';
$('#projectid').val(global.projectid);
$('#downimageconfigid').val(selected.downimageconfigid);
$('#iskeychange').val(iskeychange);
$('#isnopic').val(isnopic);
$('#form').attr("action", global.web_path + "/grid/imgconf/modimgconf.do");
$("#form").submit();
}
$('#ut_add').linkbutton('disable');
}
}, {
id: 'ut_close',
text: '退出',
handler: function () {
$('#ut_add').linkbutton('enable');
$('#imgconf-dialog').dialog('close');
}
}]
});
}
// 重置表單
function reset() {
$('#ut_add').linkbutton('enable');
if (global.operatype == 'mod') {
$('#imgconf-dialog').dialog('setTitle', '修改');
$('#viewkey').val(selected.viewkey);
$('#type').combobox('setValue', selected.type);
$('#remark').val(selected.remark);
$('#imgconf-dialog').dialog('open');
deleteFile('file'); // 清空檔案欄位
} else {
$('#imgconf-dialog').dialog('setTitle', '添加');
$('#viewkey').val('');
$('#remark').val('');
deleteFile('file');
}
}
// 限制文字區域長度
function check() {
var content = $('#remark').val();
var len = content.length;
var maxlen = 300;
if (len > maxlen) {
alert("字數太長,已被截斷為300字!");
$('#remark').val(content.substr(0, maxlen));
}
}
// 清空 input[type=file](無法直接設值,需替換節點)
function deleteFile(file) {
var ie = (navigator.appVersion.indexOf("MSIE") != -1);
if (ie) {
refreshUploader($("input[name=" + file + "]")[0]);
} else {
$("input[name=" + file + "]").attr("value", "");
}
}
function refreshUploader(file) {
var file2 = file.cloneNode(false);
file2.onchange = file.onchange;
file.parentNode.replaceChild(file2, file);
}
// 檢查檔案大小與型別
function fileChange(target) {
// 檢查副檔名
if (!(/(\?|:jpg|gif|png|jpeg)$/i.test(target.value))) {
alert("只允許上傳 jpg|gif|png|jpeg 格式的圖片");
if (window.ActiveXObject) {
target.select();
document.selection.clear();
} else if (window.opera) {
target.type = "text";
target.type = "file";
} else {
target.value = "";
}
return;
}
// 檢查檔案大小
var isIE = /msie/i.test(navigator.userAgent) && !window.opera;
var fileSize = 0;
if (isIE && !target.files) {
var filePath = target.value;
var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
var file = fileSystem.GetFile(filePath);
fileSize = file.Size;
} else {
fileSize = target.files[0].size;
}
var size = fileSize / 1024;
if (size > 500) {
alert("文件大小不能超過500KB");
if (window.ActiveXObject) {
target.select();
document.selection.clear();
} else if (window.opera) {
target.type = "text";
target.type = "file";
} else {
target.value = "";
}
return;
}
}
這裡有兩個值得說明的技巧。第一,出於安全性考量,input[type=file] 的值無法用 JavaScript 設定,因此「清空」只能替換掉整個節點(cloneNode 後 replaceChild),並記得把 onchange 複製過去。第二,判斷副檔名的那段正則有問題,正確寫法應該是 /\.(jpe?g|gif|png)$/i,原寫法並未真正比對副檔名。
/**
* 新增下載圖片配置
*/
@RequestMapping(value = "/grid/imgconf/addimgconf",
method = {RequestMethod.POST, RequestMethod.GET},
produces = {"text/html;charset=UTF-8"})
@ResponseBody
public String addImgConf(HttpServletRequest request, HttpServletResponse response,
BindException errors) throws IOException {
String m = "00";
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
response.setHeader("Access-Control-Allow-Origin", "*");
String projectid = Function.dealNull(multipartRequest.getParameter("projectid"));
String viewKey = Function.dealNull(multipartRequest.getParameter("viewkey"));
String type = Function.dealNull(multipartRequest.getParameter("type"));
String remark = Function.dealNull(multipartRequest.getParameter("remark"));
try {
// 唯一性檢查
int size = imgConfService.getImgConfsCount(Constants.DEF_STRING_NULL, projectid,
viewKey, Constants.STATUS_ON);
if (size > 0) {
m = "02";
logger.info("已存在的控件標識!");
return "<textarea>" + m + "</textarea>";
}
// 上傳圖片
Map<String, String> picInfo = imgConfService.uploadImage(fileMap);
imgConfService.addImgConf(UUID.randomUUID().toString(), projectid, viewKey, type,
remark, picInfo.get("URL"), Constants.STATUS_ON);
m = "00";
logger.info("添加下載圖片配置成功!");
} catch (Exception e) {
m = "01";
logger.error("添加下載圖片配置失敗", e);
}
// 以 textarea 包住回應,解決 IE 下 submit 後未執行 success 回呼的問題
// (這是 jquery easyui form 的已知 bug)
return "<textarea>" + m + "</textarea>";
}
最後那個 <textarea> 包裝是個典型的歷史包袱:easyui 的 form success 回呼是靠讀取 iframe 內新文件的內容來運作,而 IE 對某些回應型別的處理方式不同,導致回呼不觸發,於是用 textarea 包住再搭配 produces = "text/html;charset=UTF-8" 來強制冷處理。這也說明了 iframe 上傳方案為何難以維護——它的回呼機制建立在解析文件內容之上,而非標準協定。
現在要跨網域上傳檔案,直接由後端加上 CORS 標頭,前端用 FormData 送出即可:
var fd = new FormData($('#form')[0]);
fetch(global.web_path + "/grid/imgconf/addimgconf.do", {
method: 'POST',
body: fd,
credentials: 'include' // 需要帶 cookie 時加上
})
.then(r => r.json())
.then(data => {
// 直接處理 JSON,不必再拆解字串
});
伺服器端只需回應 Access-Control-Allow-Origin,若要帶 Cookie 則必須改用 credentials: 'include' 搭配 Access-Control-Allow-Credentials: true,且此時 Allow-Origin 不能寫成 *,必須明確指定來源網域。
另外提醒一點:原程式中的 response.setHeader("Access-Control-Allow-Origin", "*") 配合 Session 驗證其實存在風險——允許所有來源讀取回應,等於把受保護的資料門戶打開。跨網域設定應限制為已知的、可信任的來源清單。