spring boot2.0整合富文本編輯器Ueditor

最近在弄個人博客,初步已經做出來了 www.qiangutime.cn,歡迎大家參觀(很多界面沒畫)

個人博客需要使用到富文本編輯器,當時在markdown和ueditor兩者間選擇,但是由於外觀問題,就否決了markdown,進了ueditor的坑,弄了好幾天。

好吧,直接開始介紹我的過程。

首先工具

1.spring boot2.1.0

2.ueditor

pom引入ueditor依賴的包

		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>

這裏要指明一下ueditor的版本 1.4.3.3 ,去官網就可以下載,如圖所示。

然後由於一系列的原因,也在網上查閱了很多大佬的資料,採用的修改源碼,進而整合ueditor。

一、首先將源碼和ueditor下載,並且整合到項目中。

這裏需要將ueditor的jsp目錄中config.json放在同級目錄,將Index.html複製到templates目錄下,

然後瀏覽界面,寫UeditorController類,跳轉頁面

    @RequestMapping("/")
    private String showPage(){
        return "index";
    }

在頁面輸入localhost:8080,即可看到界面,按F12得到 請求後臺配置項http錯誤,上傳功能將不能正常使用!

二、配置ueditor

1.在UeditorController中寫config.json映射方法

@Controller
public class UEditorController {


    @RequestMapping("/")
    private String showPage(){
        return "index";
    }

    @RequestMapping(value="/config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

2.配置config.ueditor.js的ServerUrl

        //爲編輯器實例添加一個路徑,這個不能被註釋
        UEDITOR_HOME_URL: URL

        // 服務器統一請求接口路徑
        , serverUrl: URL + "config"

3.修改BinaryUploader 類,解決其無法獲得帶字節流的request的問題
打開com.baidu.ueditor.upload.BinaryUploader.java,修改爲:

public class BinaryUploader {  
  
    public static final State save(HttpServletRequest request,  
            Map<String, Object> conf) {  
        // FileItemStream fileStream = null;  
        // boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;  
  
        if (!ServletFileUpload.isMultipartContent(request)) {  
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);  
        }  
  
        // ServletFileUpload upload = new ServletFileUpload(  
            //  new DiskFileItemFactory());  
        //  
        // if ( isAjaxUpload ) {  
        //     upload.setHeaderEncoding( "UTF-8" );  
        // }  
  
        try {  
            // FileItemIterator iterator = upload.getItemIterator(request);  
            //  
            // while (iterator.hasNext()) {  
            //  fileStream = iterator.next();  
            //  
            //  if (!fileStream.isFormField())  
            //      break;  
            //  fileStream = null;  
            // }  
            //  
            // if (fileStream == null) {  
            //  return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);  
            // }  
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
            MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());  
            if(multipartFile==null){  
                return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);  
            }  
  
            String savePath = (String) conf.get("savePath");  
            //String originFileName = fileStream.getName();  
            String originFileName = multipartFile.getOriginalFilename();  
            String suffix = FileType.getSuffixByFilename(originFileName);  
  
            originFileName = originFileName.substring(0,  
                    originFileName.length() - suffix.length());  
            savePath = savePath + suffix;  
  
            long maxSize = ((Long) conf.get("maxSize")).longValue();  
  
            if (!validType(suffix, (String[]) conf.get("allowFiles"))) {  
                return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);  
            }  
  
            savePath = PathFormat.parse(savePath, originFileName);  
  
            String physicalPath = (String) conf.get("rootPath") + savePath;  
  
            //InputStream is = fileStream.openStream();  
            InputStream is = multipartFile.getInputStream();  
            State storageState = StorageManager.saveFileByInputStream(is,  
                    physicalPath, maxSize);  
            is.close();  
  
            if (storageState.isSuccess()) {  
                storageState.putInfo("url", PathFormat.format(savePath));  
                storageState.putInfo("type", suffix);  
                storageState.putInfo("original", originFileName + suffix);  
            }  
  
            return storageState;  
        // } catch (FileUploadException e) {  
        //  return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);  
        } catch (IOException e) {  
        }  
        return new BaseState(false, AppInfo.IO_ERROR);  
    }  
  
    private static boolean validType(String type, String[] allowTypes) {  
        List<String> list = Arrays.asList(allowTypes);  
  
        return list.contains(type);  
    }  
}

3.修改圖片上傳路徑,配置虛擬路徑

上傳圖片存儲,我嘗試了兩種方法,1.上傳虛擬路徑 2.上傳七牛雲。

將圖片上傳後返回外鏈給ueditor編輯器.

這裏大家可以看到imageActionName  上傳的方法名稱,和imagefieldName上傳的圖片名稱。

那麼接下來配置將圖片上傳至後臺

在index.html界面,這段代碼的意思就是當執行action爲uploadimage時,執行後臺名爲image方法,並且返回外鏈,也就是圖片的src,當然這個鏈接需要你自己定義返回值,保證鏈接有效並且頁面能夠訪問,當然多圖上傳和其它文件類型上傳都是一樣的。

<script type="text/javascript">
	var ue = UE.getEditor('editor');
	UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
	                UE.Editor.prototype.getActionUrl = function(action) {
	                    if (action == 'uploadimage') {
	                        return '/image'; //在這裏返回我們實際的上傳圖片地址
	                    } else {
	                        return this._bkGetActionUrl.call(this, action);
	                    }
	                }
</script>

 

如何上傳圖片至虛擬路徑,要注意這裏的upfile要與config.json中的上傳圖片相同,

/**
	 * @author qiangu
	 * @Date 2018年12月25日
	 * Describe:Ueditor上傳圖片至服務器返回外鏈
	 */
    @PostMapping("/image")
    @ResponseBody
    public String uploadImgQiniu(@RequestParam("upfile")MultipartFile upfile) throws IOException {
    	ObjectMapper mapper = new ObjectMapper();
		HashMap<String,Object> configs = new HashMap<String,Object>();
    	if(!upfile.isEmpty()) {
            String fileName = upfile.getOriginalFilename();
            String filePath = "C:/Users/ASUS/Desktop/file/";
            fileName = filePath+fileName;
            File dest = new File(fileName);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdir();
            }
            try {
                upfile.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
    		configs.put("state", "SUCCESS");
            //這裏的/img爲虛擬路徑,參考我的第一篇博客
    		configs.put("url", "/img/"+upfile.getOriginalFilename());
    		configs.put("title", upfile.getName());
    		configs.put("original", upfile.getOriginalFilename());
    	}else {
    		configs.put("state", "FAUIL");
    		configs.put("url", null);
    		configs.put("title", null);
    		configs.put("original", null);
    	}
		return mapper.writeValueAsString(configs);
    }

接下來看下效果,

 此時圖片路徑爲/img/message-1.jpg,成功。

本文參考了https://www.jianshu.com/p/231e83c13610

如有侵權,請聯繫本人,將立即刪除。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章