我們可自訂工具列按鈕使simditor實現更豐富和實現上傳圖片功能
初始化編輯器
<script type="text/javascript"> $(function(){ toolbar = [ 'title', 'bold', 'italic', 'underline', 'strikethrough', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent' ]; var editor = new Simditor( { textarea : $('#editor'), placeholder : '這裡輸入內容...', toolbar : toolbar, //工具列 defaultImage : 'simditor-2.0.1/images/image.png', //編輯器插入圖片時使用的預設圖片 upload : { url : 'ImgUpload.action', //檔案上傳的介面地址 params: null, //索引值對,指定檔案上傳介面的額外參數,上傳的時候隨檔案一起提交 fileKey: 'fileDataFileName', //伺服器端擷取檔案資料的參數名 connectionCount: 3, leaveConfirm: '正在上傳檔案' } }); })</script>
upload預設為false,設定為true或者索引值對就可以實現上傳圖片,介面是出來了,還需要進行後台編碼(本例為Struts2)
實現功能之前需要修改一下simditor.js,我們可以對"本地圖片" 用chrome審查元素髮現沒有name屬性
開啟simditor.js找到
return $input = $('<input type="file" title="' + Simditor._t('uploadImage') + '" accept="image/*">').appendTo($uploadItem);這一行,
可以搜尋accept="image/*" 快速找到在input裡加上 name="fileData"
如下:
return _this.input = $('<input name="fileData" type="file" title="' + Simditor._t('uploadImage') + '" accept="image/*">').appendTo($uploadBtn);
同樣繼續搜尋accept="image/*" 下面還有一個,加上name="fileData"
ImgUploadAction
public class ImgUploadAction extends ActionSupport { private static final long serialVersionUID = 1L; private String err = ""; private String msg; //返回資訊 private File fileData; //上傳檔案 private String fileDataFileName; //檔案名稱 public String imgUpload() { //擷取response、request對象 ActionContext ac = ActionContext.getContext(); HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); response.setContentType("text/html;charset=gbk"); PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e1) { e1.printStackTrace(); } String saveRealFilePath = ServletActionContext.getServletContext().getRealPath("/upload"); File fileDir = new File(saveRealFilePath); if (!fileDir.exists()) { //如果不存在 則建立 fileDir.mkdirs(); } File savefile; savefile = new File(saveRealFilePath + "/" + fileDataFileName); try { FileUtils.copyFile(fileData, savefile); } catch (IOException e) { err = "錯誤"+e.getMessage(); e.printStackTrace(); } String file_Name = request.getContextPath() + "/upload/" + fileDataFileName; msg = "{\"success\":\"" + true + "\",\"file_path\":\"" + file_Name + "\"}"; out.print(msg); //返回msg資訊 return null; } public String getErr() { return err; } public void setErr(String err) { this.err = err; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public File getFileData() { return fileData; } public void setFileData(File fileData) { this.fileData = fileData; } public String getFileDataFileName() { return fileDataFileName; } public void setFileDataFileName(String fileDataFileName) { this.fileDataFileName = fileDataFileName; } }
相關文章:
Simditor使用方法
javascript - simditor 上傳圖片大小有限制嗎?
javascript - simditor 上傳大圖失敗