要在後台加一個富文本輸入框,SinaEditor 這類輕量編輯器是最省事的選擇之一。它的整合方式很特別:用 textarea 佔位、用 iframe 載入真正的編輯畫面,兩者靠 id 溝通。
下載後解壓縮,核心是 editor.htm,同目錄下還有 img.htm(上傳圖片)與 attach.htm(上傳附件)。後兩者操作邏輯幾乎相同,都可以視為「上傳檔案」的介面。
<textarea name="problemBody" id="content" style="display:none;"></textarea>
<iframe
src="<%=request.getContextPath() %>/edit/editor.htm?id=content&ReadCookie=0"
frameBorder="0" marginHeight="0" marginWidth="0"
scrolling="No" width="621" height="457">
</iframe>
兩個關鍵點:src 要指向你實際放置 editor.htm 的路徑;查詢參數 id=content 必須與 textarea 的 id 完全一致——編輯器就是靠這個 id 找到並回填那個隱藏的 textarea。若打開後內容寫不回表單,九成是這個 id 對不上。
function chk_imgpath() {
if ($('radio1').checked == true) {
// 使用者直接貼圖片網址
if ($("imgpath").value == "https://" || $("imgpath").value == "") {
window.close();
return;
}
LoadIMG($("imgpath").value);
} else {
// 使用者要上傳本機檔案
if ($("file1").value == "") {
alert("請選擇上傳圖片文件!");
return;
}
var filepath = j("#file1").val();
var filetype = filepath.substring(filepath.lastIndexOf('.'));
var regu = ".gif.jpg.png.jpge.GIF.JPG.PNG";
if (regu.indexOf(filetype) == -1) {
alert('只允許上傳 .gif / .jpg / .png 類型文件!');
return;
}
j.ajaxFileUpload({
type: 'POST',
secureuri: false,
fileElementId: 'file1',
url: '/ask/fileUpload?type=img',
dataType: 'String',
success: function (data) {
j("#imgpath").attr("value", data); // 把回傳路徑寫進欄位
j("#radio1").attr("checked", "true");
chk_imgpath(); // 再走一次上面的流程
$('divProcessing').style.display = '';
},
error: function (data) { alert('文件上傳失敗'); }
});
}
}
這段程式示範了一個實用的遞迴模式:上傳成功後,把伺服器回傳的路徑填進「圖片網址」欄位、把單選鈕切到「使用網址」,然後再呼叫自己一次。第二次進入時走的是上面的分支,直接載入圖片。這樣就不必在上傳成功後重寫一遍載入邏輯。
副檔名比對太粗糙。regu.indexOf(filetype) 用子字串搜尋,".gif.jpg.png" 裡要找 gif(少了點)也會命中;而 .jpge 是 .jpeg 的誤拼,會把真正的 JPEG 擋掉。改用 /\.(gif|jpe?g|png)$/i.test(filepath) 更準確。
只看副檔名不等於安全。真正的型別檢查必須在伺服器端做(讀取檔案簽名而非檔名),並限制大小、重新編碼圖片,否則仍可上傳偽裝的檔案。
attr 應改為 prop。設定 checked 用 .prop("checked", true),理由與核取方塊相同。
後端提供 /ask/fileUpload 這類端點,接收 multipart 上傳、存檔、回傳可存取的 URL 字串即可。編輯器提交的內容則從 problemBody 這個欄位取得,寫入資料庫前務必做 HTML 白名單消毒,避免儲存型 XSS。