【UEditor】 UEditor整合項目上傳資源到阿里雲服務器

 

目錄javascript

關於此文

  項目中要實現編輯器生成帶格式的html文檔,存入模板,最後生成html的URL,因此選擇了UEditor。css

     UEditor是由百度WEB前端研發部開發的所見即所得的開源富文本編輯器,具備輕量、可定製、用戶體驗優秀等特色。html

     以前沒有接觸過編輯器,從頭開始摸索。看API,看網上的例子。以前,用的是UMeditor,是UEditor的mini版本。用的人少,例子也少。讓我很苦惱。以後又換回了完整版。前端

  官網地址:http://ueditor.baidu.com/website/index.htmljava

下載源碼

  源碼下載地址:http://ueditor.baidu.com/website/download.htmljquery

  

  我是JSP版本。ueditor1_4_3-utf8-jsp,解壓後,放入工程中。nginx

  

  將ueditor/jsp/lib下的jar包導入WEB-INF下lib下,maven工程導入外部jar方法,以下:web

  

  例子:spring

        <dependency>  
            <groupId>cn.com.umeditor</groupId>  
            <artifactId>json</artifactId>  
            <version>1.0</version>  
            <scope>system</scope>  
            <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/json.jar</systemPath>  
        </dependency> 

 

JSP代碼

  編輯本身的JSP頁面:數據庫

  

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>惠民網消息推送平臺</title>
    <meta charset="utf-8">
     <script  src="<%=request.getContextPath() %>/ueditor/ueditor.config.js"></script>
     <script  src="<%=request.getContextPath() %>/ueditor/ueditor.all.min.js"></script>
     <script  src="<%=request.getContextPath() %>/ueditor/lang/zh-cn/zh-cn.js"></script>
    <script  src="<%=request.getContextPath() %>/ueditor/third-party/jquery-1.10.2.min.js"></script>
    <link href="<%=request.getContextPath() %>/ueditor/themes/iframe.css" type="text/css" rel="stylesheet">
    <link href="<%=request.getContextPath() %>/ueditor/themes/default/css/ueditor.css" type="text/css" rel="stylesheet">
    <link href="<%=request.getContextPath() %>/ueditor/third-party/codemirror/codemirror.css" type="text/css" rel="stylesheet">
</head>
 <style type="text/css">
        div{
            width:100%;
        }
    </style>
<body>  
<form method="post" action="<%=request.getContextPath() %>/test/test.do">
    <br>類別:<input type="text" name="stype" />
    標題:<input type="text" name="title" /> <br/>
    <!--style給定寬度能夠影響編輯器的最終寬度-->
    <!-- 加載編輯器的容器 -->
    <!-- 實例化編輯器 -->
    <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
    <script type="text/javascript">
        var ue = UE.getEditor('editor');
    </script>
    
    <input type="submit" value="提交"/>
</form>
</body>
</html>

遇到的錯誤:1)var ue = UE.getEditor('editor'); 報錯緣由:js引入錯誤,路徑錯誤/引入順序錯誤。

         2)表情包,html頁面都是404.路徑都對,文件也存在,就是找不到。錯誤緣由:spring攔截器問題。(表情包要再官網下載後導入到程序中,下載的包裏面有很詳細的導入方法。)

        

 

錯誤解決就能夠啓動tomcat進行展現頁面了。

Java代碼

  因爲上傳圖片/上傳文件都保存到本地的tomcat下,下次啓動,文件/圖片就會消失。根據業務需求,都是把圖片/文件存到服務器下。或者本地的其它路徑。

  而後UEditor的上傳代碼都是寫到源碼中了。讓我一陣糾結。百度了一下,搜到了一個很是棒的例子,符合我項目,符合框架,什麼都符合,下載源碼進行實驗。

  源碼下載地址:http://download.csdn.net/detail/qq457557442/8322227  

  博客地址:http://blog.csdn.net/wang_jingj

  上代碼

  action:

package getui.controller;

import getui.util.FileUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


@Controller
@RequestMapping(value = "/test")
public class testController {

    // 文件上傳路徑
    @Resource(name="fileuploadPath")
    private String fileuploadPath;
   
    // 文件讀取路徑
    @Resource(name="httpPath")
    private String httpPath;
    
    /**
     * 文件上傳Action
     * @param req APPLICATION_JSON_VALUE
     * @return UEDITOR 須要的json格式數據
     */
    @RequestMapping(value = "/test.do")
    @ResponseBody
    public Map<String,Object> upload(HttpServletRequest req){
        Map<String,Object> result = new HashMap<String, Object>();
        
        MultipartHttpServletRequest mReq  =  null;
        MultipartFile file = null;
        InputStream is = null ;
        String fileName = "";
        // 原始文件名   UEDITOR建立頁面元素時的alt和title屬性
        String originalFileName = "";
        String filePath = "";
        
        try {
            mReq = (MultipartHttpServletRequest)req;
            // 從config.json中取得上傳文件的ID
            file = mReq.getFile("upfile");
            // 取得文件的原始文件名稱
            fileName = file.getOriginalFilename();

            originalFileName = fileName;
            
            if(!fileName.isEmpty()){
                is = file.getInputStream();
                fileName = FileUtils.reName(fileName);
                filePath = FileUtils.saveFile(fileName, is, fileuploadPath);
            } else {
                throw new IOException("文件名爲空!");
            }
            
            result.put("state", "SUCCESS");// UEDITOR的規則:不爲SUCCESS則顯示state的內容
            result.put("url",httpPath + filePath);
            result.put("title", originalFileName);
            result.put("original", originalFileName);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            result.put("state", "文件上傳失敗!");
            result.put("url","");
            result.put("title", "");
            result.put("original", "");
            System.out.println("文件 "+fileName+" 上傳失敗!");
        }
        
        return result;
    }
}

  工具包

package getui.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 * 文件上傳/圖片上傳 工具類
 * FileUtils.java
 * 
 * @author Anny
 *
 */
public class FileUtils {
    /**
     * 文件copy方法
     * @param src
     * @param dest
     */
    public static void copy(InputStream src, OutputStream dest) {
        try {
            byte[] tmp = new byte[1024];
            int len = -1;
            while ((len = src.read(tmp)) != -1)
                dest.write(tmp, 0, len);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 給文件重命名 防止覆蓋
     * @param fileName
     * @return 時間戳+原始文件的後綴
     */
    public static String reName(String fileName){
        return new StringBuffer().append(new Date().getTime()).append(fileName.substring(fileName.indexOf("."))).toString();
    }
    
    /**
     * 文件保存
     * @param fileName reName以後的文件名稱
     * @param content 
     * @param filePath 文件保存路徑
     * @return 
     * @throws IOException
     */
    public static String saveFile(String fileName,InputStream content,String filePath) throws IOException {
        FileOutputStream fos = null;
        StringBuffer contentPath =  new StringBuffer("");; // 上下文地址
        try {
            contentPath.append("detail/");     
//            contentPath.append("/");  
            contentPath.append(fileName);       // 
            
            File pictureFile = new File(filePath + contentPath.toString());
            File pf = pictureFile.getParentFile();
            if(!pf.exists()){
                pf.mkdirs();
            }
            pictureFile.createNewFile();    // 建立文件
            fos = new FileOutputStream(pictureFile);
            FileUtils.copy(content, fos);
            
            
            // 上傳到OSS
            UploadOSSUtil.uploadImgAliyun(content,
                    pictureFile.length(), contentPath.toString());
            
    
        } catch (Exception e) {
            throw new IOException("文件保存失敗!");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    throw new IOException("文件保存失敗!");
                }
            }
        }
        return contentPath.toString();
    }
}

  JSP

  

 <script>
//編輯器資源文件根路徑 最好在ueditor.config.js中配置
window.UEDITOR_HOME_URL = "/getui-huimin/ueditor/";
//建議使用工廠方法getEditor建立和引用編輯器實例,若是在某個閉包下引用該編輯器,直接調用UE.getEditor('editor')就能拿到相關的實例
var ue = UE.getEditor('editor',{initialFrameHeight: 500,initialFrameWidth:800,maximumWords:3000,elementPathEnabled:false});
//複寫UEDITOR的getActionUrl 方法,定義本身的Action
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function(action) {
    if (action == 'uploadimage' || action == 'uploadfile') {
        var id = $('#carInfoId').val();
           return '<%=request.getContextPath() %>/test/test.do';
    } else {
        return this._bkGetActionUrl.call(this, action);
    }
};
// 複寫UEDITOR的getContentLength方法 解決富文本編輯器中一張圖片或者一個文件只能算一個字符的問題,可跟數據庫字符的長度配合使用
UE.Editor.prototype._bkGetContentLength = UE.Editor.prototype.getContentLength;
UE.Editor.prototype.getContentLength = function(){
    return this.getContent().length;
}
</script>  

阿里雲jar包引入配置

阿里雲jar引入

<!-- aliyun -->
        <dependency>
            <groupId>com.aliyun.openservices</groupId>
            <artifactId>aliyun-openservices</artifactId>
            <version>1.0.10</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-core</artifactId>
                <version>2.1.6</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-sts</artifactId>
                <version>2.1.0</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-yundun</artifactId>
                <version>2.1.3</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-slb</artifactId>
                <version>2.0.0-rc1</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-oms</artifactId>
                <version>2.0.1</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-ecs</artifactId>
                <version>2.0.0-rc2</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-rds</artifactId>
                <version>2.0.0-rc1</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-bss</artifactId>
                <version>2.0.0-rc1</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-ocs</artifactId>
                <version>2.0.0-rc1</version>
        </dependency>
        <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>aliyun-java-sdk-cms</artifactId>
                <version>2.0.0</version>
        </dependency>
        <!-- aliyun -->

spring配置文件:

<bean id="fileuploadPath" class="java.lang.String">
        <constructor-arg index="0" value="${fileuploadPath}"></constructor-arg>
    </bean>
    
    <bean id="httpPath" class="java.lang.String">
        <constructor-arg index="0" value="${httpPath}"></constructor-arg>
    </bean>
    
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
    </bean>

config.properties

#file upload path
fileuploadPath=F:/worksoft/nginxfilepath  -- 本地目錄
#file read path
httpPath=http://rexs.xxx.cn/               
 --讀取回顯的地址:阿里雲服務器地址

成功啦!

一切準備就緒,開始上傳。

顯示上傳到本地 保存一份後,在進行服務器上傳。

前兩個 因爲網絡,上傳阿里雲失敗。本地保存成功。

後一個 上傳成功了。成功後回顯回來。

訪問阿里雲服務器圖片地址,可以下載到圖片。^_^

相關文章
相關標籤/搜索