ueditor上傳圖片視頻Java-前後端分離

1、本人下載版本號是:1.4.3.3 完整源碼,後臺需要改的東西。

(1)完整版本里有源碼:ueditor-1.4.3.3\ueditor-1.4.3.3\jsp\src,下面所有源碼複製到項目src下面。

(2)找到BinaryUploader類用以下代碼替換。

package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class BinaryUploader {

   public static final State save(HttpServletRequest request,
                           Map<String, Object> conf) {
      if (!ServletFileUpload.isMultipartContent(request)) {
         return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
      }
      try {
         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;
         String physicalPath = (String)conf.get("basePath")+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 (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)把config.json移到resources下面。

(4)找到ConfigManager類初始化方法,用以下替換initEnv。防止後臺從resources下面加載config.json出錯

private void initEnv () throws FileNotFoundException, IOException {
   
   File file = new File( this.originalPath );
   
   if ( !file.isAbsolute() ) {
      file = new File( file.getAbsolutePath() );
   }
   
   this.parentPath = file.getParent();
   
   //String configContent = this.readFile( this.getConfigPath() );
   String configContent = this.filter(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("config.json")));

   try{
      JSONObject jsonConfig = new JSONObject( configContent );
      this.jsonConfig = jsonConfig;
   } catch ( Exception e ) {
      this.jsonConfig = null;
   }
   try{
      JSONObject jsonConfig = new JSONObject( configContent );
      this.jsonConfig = jsonConfig;
   } catch ( Exception e ) {
      this.jsonConfig = null;
   }
   
}

還有getConfig ,把basePath加入conf中,爲config.json做鋪墊。

public Map<String, Object> getConfig ( int type ) {
   
   Map<String, Object> conf = new HashMap<String, Object>();
   String savePath = null;
   
   switch ( type ) {
   
      case ActionMap.UPLOAD_FILE:
         conf.put( "isBase64", "false" );
         conf.put( "maxSize", this.jsonConfig.getLong( "fileMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "fileFieldName" ) );
         savePath = this.jsonConfig.getString( "filePathFormat" );
         break;
         
      case ActionMap.UPLOAD_IMAGE:
         conf.put( "isBase64", "false" );
         conf.put( "maxSize", this.jsonConfig.getLong( "imageMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "imageFieldName" ) );
         savePath = this.jsonConfig.getString( "imagePathFormat" );
         break;
         
      case ActionMap.UPLOAD_VIDEO:
         conf.put( "maxSize", this.jsonConfig.getLong( "videoMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "videoFieldName" ) );
         savePath = this.jsonConfig.getString( "videoPathFormat" );
         break;
         
      case ActionMap.UPLOAD_SCRAWL:
         conf.put( "filename", ConfigManager.SCRAWL_FILE_NAME );
         conf.put( "maxSize", this.jsonConfig.getLong( "scrawlMaxSize" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "scrawlFieldName" ) );
         conf.put( "isBase64", "true" );
         savePath = this.jsonConfig.getString( "scrawlPathFormat" );
         break;
         
      case ActionMap.CATCH_IMAGE:
         conf.put( "filename", ConfigManager.REMOTE_FILE_NAME );
         conf.put( "filter", this.getArray( "catcherLocalDomain" ) );
         conf.put( "maxSize", this.jsonConfig.getLong( "catcherMaxSize" ) );
         conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) );
         conf.put( "fieldName", this.jsonConfig.getString( "catcherFieldName" ) + "[]" );
         savePath = this.jsonConfig.getString( "catcherPathFormat" );
         break;
         
      case ActionMap.LIST_IMAGE:
         conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) );
         conf.put( "dir", this.jsonConfig.getString( "imageManagerListPath" ) );
         conf.put( "count", this.jsonConfig.getInt( "imageManagerListSize" ) );
         break;
         
      case ActionMap.LIST_FILE:
         conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) );
         conf.put( "dir", this.jsonConfig.getString( "fileManagerListPath" ) );
         conf.put( "count", this.jsonConfig.getInt( "fileManagerListSize" ) );
         break;
         
   }
   //將basePath塞進conf
   conf.put("basePath",this.jsonConfig.getString("basePath"));
   conf.put( "savePath", savePath );
   conf.put( "rootPath", this.rootPath );
   
   return conf;
   
}

(5)自定義控制層類替換controller.jsp,代碼如下

package com.foodo.cloud.admin.modules.web.controller;

import com.baidu.ueditor.ActionEnter;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName FileUploadController
 * @Description TODO
 * @Author zhaodaolin
 * @Date 2018/7/26 16:01
 * @Version 1.0
 */
@RestController
@RequestMapping("web/fileUpload")
public class FileUploadController {
    //處理文件上傳
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public Map<String, Object> uploadimage(@RequestParam("file") MultipartFile upfile){
        Map<String, Object> params = new HashMap<String, Object>();
        try{

            String basePath = "";//物理路徑
            String visitUrl = "";//服務器路徑
            //爲了方便的上傳和管理圖片,我在服務器中配置了專門的圖片存取路徑。即在tomcat
            //的server.xml中添加一句 <Context docBase="d:/assets" path="/assets" reloadable="true"/>
            String ext;
            String name = upfile.getOriginalFilename();
            if(name == null || "".equals(name) || !name.contains("."))
                ext = "";
            else{
                ext = name.substring(name.lastIndexOf(".")+1);
            }
            String fileName = String.valueOf(System.currentTimeMillis()).concat("_").concat(String.valueOf(RandomUtils.nextInt(0, 6))).concat(".").concat(ext);
            StringBuilder sb = new StringBuilder();
            //拼接保存路徑
            sb.append(basePath).append(fileName);
            visitUrl = visitUrl.concat(fileName);
            File f = new File(sb.toString());
            if(!f.exists()){
                f.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(f);
            FileCopyUtils.copy(upfile.getInputStream(), out);
            params.put("state", "SUCCESS");
            params.put("url", visitUrl);
            params.put("size", upfile.getSize());
            params.put("original", fileName);
            params.put("type", upfile.getContentType());
        } catch (Exception e){
            params.put("state", "ERROR");
        }
        return params;
    }


    @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();
        }

    }

    private void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
}

(6)linux及windows資源映射。

package com.foodo.cloud.admin.common.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;

/**
 * WebMvc配置
 *
 * @author Mark [email protected]
 * @since 3.0.0 2018-01-25
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        //window下映射,tomcat直接用路徑訪問
        //registry.addResourceHandler("/**").addResourceLocations("file:"+"D:/");
        //linux下映射,tomcat直接用路徑訪問,表示映射fooUpload下面所有文件
        registry.addResourceHandler("/**").addResourceLocations("file:"+"/fooUpload/");
        //registry.addResourceHandler("/**").addResourceLocations("file:"+"/");
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();

        //生成json時,將所有Long轉換成String
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(0, jackson2HttpMessageConverter);
    }
}

以上就是後臺需要配置的代碼,現在看前端。

(1)下載1.4.3.3 Jsp 版本代碼:在resources文件下新建statics/ueditor文件,把ueditor1_4_3_3-utf8-jsp\utf8-jsp下面所有文件都放在ueditor中。lib下面所有包在maven中引用,除啦ueditor.jar外,因爲我們後臺已有源碼,故不用引用它。

(2)config.json配置文件改成心下。

/* 前後端通信相關的配置,註釋只允許使用多行方式 */
{
    /* 上傳圖片配置項 */
    /*"basePath": "D:/",*/ /* windows */
    "basePath": "/fooUpload", /* linux */
    "imageActionName": "uploadimage", /* 執行上傳圖片的action名稱 */
    "imageFieldName": "upfile", /* 提交的圖片表單名稱 */
    "imageMaxSize": 2048000, /* 上傳大小限制,單位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */
    "imageCompressEnable": true, /* 是否壓縮圖片,默認是true */
    "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */
    "imageInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageUrlPrefix": "http://192.168.254.37:8080", /* 圖片訪問路徑前綴 */
    "imagePathFormat": "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
                                /* {filename} 會替換成原文件名,配置這項需要注意中文亂碼問題 */
                                /* {rand:6} 會替換成隨機數,後面的數字是隨機數的位數 */
                                /* {time} 會替換成時間戳 */
                                /* {yyyy} 會替換成四位年份 */
                                /* {yy} 會替換成兩位年份 */
                                /* {mm} 會替換成兩位月份 */
                                /* {dd} 會替換成兩位日期 */
                                /* {hh} 會替換成兩位小時 */
                                /* {ii} 會替換成兩位分鐘 */
                                /* {ss} 會替換成兩位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具請體看線上文檔: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 塗鴉圖片上傳配置項 */
    "scrawlActionName": "uploadscrawl", /* 執行上傳塗鴉的action名稱 */
    "scrawlFieldName": "upfile", /* 提交的圖片表單名稱 */
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上傳大小限制,單位B */
    "scrawlUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "scrawlInsertAlign": "none",

    /* 截圖工具上傳 */
    "snapscreenActionName": "uploadimage", /* 執行上傳截圖的action名稱 */
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
    "snapscreenUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "snapscreenInsertAlign": "none", /* 插入的圖片浮動方式 */

    /* 抓取遠程圖片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 執行抓取遠程圖片的action名稱 */
    "catcherFieldName": "source", /* 提交的圖片列表表單名稱 */
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
    "catcherUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "catcherMaxSize": 2048000, /* 上傳大小限制,單位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取圖片格式顯示 */

    /* 上傳視頻配置 */
    "videoActionName": "uploadvideo", /* 執行上傳視頻的action名稱 */
    "videoFieldName": "upfile", /* 提交的視頻表單名稱 */
    "videoPathFormat": "/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
    "videoUrlPrefix": "http://192.168.254.37:8080", /* 視頻訪問路徑前綴 */
    "videoMaxSize": 102400000, /* 上傳大小限制,單位B,默認100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上傳視頻格式顯示 */

    /* 上傳文件配置 */
    "fileActionName": "uploadfile", /* controller裏,執行上傳視頻的action名稱 */
    "fileFieldName": "upfile", /* 提交的文件表單名稱 */
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
    "fileUrlPrefix": "", /* 文件訪問路徑前綴 */
    "fileMaxSize": 51200000, /* 上傳大小限制,單位B,默認50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上傳文件格式顯示 */

    /* 列出指定目錄下的圖片 */
    "imageManagerActionName": "listimage", /* 執行圖片管理的action名稱 */
    "imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出圖片的目錄 */
    "imageManagerListSize": 20, /* 每次列出文件數量 */
    "imageManagerUrlPrefix": "", /* 圖片訪問路徑前綴 */
    "imageManagerInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件類型 */

    /* 列出指定目錄下的文件 */
    "fileManagerActionName": "listfile", /* 執行文件管理的action名稱 */
    "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目錄 */
    "fileManagerUrlPrefix": "", /* 文件訪問路徑前綴 */
    "fileManagerListSize": 20, /* 每次列出文件數量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件類型 */

}

對config.json進行以下說明。

1)新加basePath路徑,以後上傳的文件都在這下面。

2)"imageActionName": "uploadimage", /* 執行上傳圖片的action名稱 */,"videoActionName": "uploadvideo", /* 執行上傳視頻的action名稱 */,等action,名字不要做任何修改。我們自己寫的config類,是根據action名稱不同做相應的轉換。

3)imageUrlPrefix:圖片訪問路徑前綴需要改你訪問項目的路徑。

4)imagePathFormat:/upload/image/......保存路徑是,basePath+imagePathFormat=/fooUpload/upload/image/.....,圖片訪問路徑就是前綴+保存路徑。

5)找到ueditor.config.js,裏面有serverUrl 改成以下。

  var RealUrl =  "http://192.168.254.37:8080";//真實的RealUrl是項目訪問的路徑
   /**
    * 配置項主體。注意,此處所有涉及到路徑的配置別遺漏URL變量。
    */
   window.UEDITOR_CONFIG = {

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

       // 服務器統一請求接口路徑,/web/fileUpload/config就是前面自己寫的類:FileUploadController 
       , serverUrl: RealUrl + "/web/fileUpload/config"

      }

到此爲止ueditor完全配置好,可以愉快的訪問啦。

2、ueditor 解決視頻回顯 src鏈接丟失問題

解決:ueditor.config.js 365 行,whiteList  拼錯了 whitList---》whiteList

參考url:

1、https://blog.csdn.net/qq_33745799/article/details/70031641

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