ueditor 上傳文件到ftp

首先下載ue 請上官網自行下載

項目文件目錄爲



修改ueditor.config.js 文件 的serverUrl  

變成

serverUrl: getRealPath()+"/getUeditorConfig"

/**
 * 獲取項目絕對路徑
 *  http://127.0.0.1:8089/xxxx
 * @returns {string}
 */
function getRealPath() {
    var localObj = window.location;
    var contextPath = localObj.pathname.split("/")[1];
    var basePath = localObj.protocol + "//" + localObj.host + "/" + contextPath;
    return basePath;
}

修改config.json

添加兩個參數

"useFtpUpload": "true", /* 是否使用FTP上傳 */
"keepLocalFile": "false", /* 使用FTP上傳後本地服務器是否保存 */

完整文件

/* 前後端通信相關的配置,註釋只允許使用多行方式 */
{
    "useFtpUpload": "true", /* 是否使用FTP上傳 */
    "keepLocalFile": "false", /* 使用FTP上傳後本地服務器是否保存 */

    /* 上傳圖片配置項 */
    "imageActionName": "uploadimage", /* 執行上傳圖片的action名稱 */
    "imageFieldName": "upfile", /* 提交的圖片表單名稱 */
    "imageMaxSize": 2048000, /* 上傳大小限制,單位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */
    "imageCompressEnable": true, /* 是否壓縮圖片,默認是true */
    "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */
    "imageInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageUrlPrefix": "http://localhost:8090/boot/showPhotoUE?path=", /* 圖片訪問路徑前綴 */
    "imagePathFormat": "/ueditor/jsp/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": "http://localhost:8090/boot/showPhotoUE?path=", /* 圖片訪問路徑前綴 */
    "scrawlInsertAlign": "none",

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

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

    /* 上傳視頻配置 */
    "videoActionName": "uploadvideo", /* 執行上傳視頻的action名稱 */
    "videoFieldName": "upfile", /* 提交的視頻表單名稱 */
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
    "videoUrlPrefix": "http://localhost:8090/boot/showPhotoUE?path=", /* 視頻訪問路徑前綴 */
    "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": "http://localhost:8090/boot/showPhotoUE?path=", /* 文件訪問路徑前綴 */
    "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": "http://localhost:8090/boot/showPhotoUE?path=", /* 圖片訪問路徑前綴 */
    "imageManagerInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件類型 */

    /* 列出指定目錄下的文件 */
    "fileManagerActionName": "listfile", /* 執行文件管理的action名稱 */
    "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目錄 */
    "fileManagerUrlPrefix": "http://localhost:8090/boot/showPhotoUE?", /* 文件訪問路徑前綴 */
    "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"
    ] /* 列出的文件類型 */

}

找到ueditor..jar包

下載地址》》》 ueditor.jar


添加到項目

找到actionenter文件


找到uploader 文件



創建FtpUploader 類

package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
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.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * Created by Administrator on 2018/5/29.
 */
public class FtpUploader
{

    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, 5);
        }

        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory());

        if (isAjaxUpload) {
            upload.setHeaderEncoding("UTF-8");
        }
        try
        {
            String org="";
            InputStream ips = null;
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList = multipartRequest.getFiles("upfile");
            for (MultipartFile m:fileList
                 ) {
                org = m.getOriginalFilename();
                ips = m.getInputStream();
            }

            if (fileList.size() <= 0) {
                return new BaseState(false, 7);
            }

            String savePath = (String)conf.get("savePath");
            String originFileName = org;
            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, 8);
            }

            savePath = PathFormat.parse(savePath, originFileName);

            String remoteDir = "";

            int pos = savePath.lastIndexOf("/");
            if(pos > -1){
                remoteDir = savePath.substring(0,pos + 1);
            }

            String physicalPath = (String)conf.get("rootPath") + savePath;

            boolean keepLocalFile = "false".equals(conf.get("keepLocalFile")) ? false : true;
            InputStream is = ips;
            State storageState = StorageManager.saveFtpFileByInputStream(is, remoteDir,
                    physicalPath, maxSize, keepLocalFile);
            is.close();

            if (storageState.isSuccess()) {
                //storageState.putInfo("url", savePath);
                storageState.putInfo("type", suffix);
                storageState.putInfo("original", originFileName + suffix);
            }

            return storageState;
        } catch (IOException localIOException) {
        }
        return new BaseState(false, 4);
    }

    @SuppressWarnings("rawtypes")
    private static boolean validType(String type, String[] allowTypes) {
        List list = Arrays.asList(allowTypes);

        return list.contains(type);
    }
}

修改

StorageManager 文件



ftpUtils 文件請看我 

》》》》 ftp工具

最後在controller添加

@ResponseBody
@RequestMapping(value = "/getUeditorConfig")
public String getUed(HttpServletRequest request,HttpServletResponse response) {
    String json="";
    try {
        //String rootPath=request.getServletContext().getRealPath("/");
        String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        //System.out.println(request.getParameter("action"));
        json = new ActionEnter( request, rootPath+"static\\content\\plugins\\ueditor\\" ).exec();;
        logger.info(json);
    } catch (Exception ex) {
        logger.error("showPhoto -=- {}", ex.toString());
    }
    return json;
}

地址對應自己的ueditor目錄即可


到此  ftp上傳就可以了

/**
 * UEditor 查看圖片使用
 * @param response
 * @param path
 */
@RequestMapping("/showPhotoUE")
public void showPhotoUE(HttpServletResponse response, String path) {
    try {
        String newPath = "";
        if (path.contains("?") && StringUtils.isNotEmpty(path)){
            newPath = path.substring(0,path.lastIndexOf("?"));
        }else {
            newPath = path;
        }
        if (StringUtils.isNotEmpty(newPath)) {
            //Thread.sleep(500);
            new FtpUtils().showPhoto(response, newPath);
        }
    } catch (Exception ex) {
        logger.error("showPhoto -=- {}", ex.toString());
    }
}


添加方法   爲了會顯示照片使用



查看在線照片功能

FileManager 類

public State listFile ( int index ) {
    List list = new ArrayList();
       try {
           list = new FtpUtils().getFileListNext(this.dir);
       } catch (IOException e) {
           e.printStackTrace();
       }
       //File dir = new File( this.dir );
   State state = null;

   /*if ( !dir.exists() ) {
      return new BaseState( false, AppInfo.NOT_EXIST );
   }
   
   if ( !dir.isDirectory() ) {
      return new BaseState( false, AppInfo.NOT_DIRECTORY );
   }*/
   
   //Collection<File> list = FileUtils.listFiles( dir, this.allowFiles, true );
   
   if ( index < 0 || index > list.size() ) {
      state = new MultiState( true );
   } else {
      Object[] fileList = Arrays.copyOfRange( list.toArray(), index, index + this.count );
      state = this.getState( fileList );
   }
   
   state.putInfo( "start", index );
   state.putInfo( "total", list.size() );
   
   return state;
   
}

修改主要部分

在修改

private State getState ( Object[] files ) {
   
   MultiState state = new MultiState( true );
   BaseState fileState = null;
   
   File file = null;
   
   for ( Object obj : files ) {
      if ( obj == null ) {
         break;
      }
      //file = (File)obj;
      fileState = new BaseState( true );
      //fileState.putInfo( "url", PathFormat.format( this.getPath( file ) ) );
           fileState.putInfo( "url", (String) obj);
      state.addState( fileState );
   }
   
   return state;
   
}

這就實現了 圖片查看功能



base64  塗鴉上傳修改

public final class Base64Uploader {

    public static State save(String content, Map<String, Object> conf) {

        byte[] data = decode(content);

        long maxSize = ((Long) conf.get("maxSize")).longValue();

      if (!validSize(data, maxSize)) {
            return new BaseState(false, AppInfo.MAX_SIZE);
      }

        String suffix = FileType.getSuffix("JPG");

        String savePath = PathFormat.parse((String) conf.get("savePath"),
                (String) conf.get("filename"));

        savePath = savePath + suffix;
        boolean keepLocalFile = "false".equals(conf.get("keepLocalFile")) ? false : true;
        State storageState = StorageManager.saveBinaryFile(data, savePath, keepLocalFile);

        if (storageState.isSuccess()) {
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", "");
        }

        return storageState;
    }

    private static byte[] decode(String content) {
        return Base64.decodeBase64(content);
    }


    private static boolean validSize(byte[] data, long length) {
        return data.length <= length;
    }

}


public static State saveBinaryFile(byte[] data, String path, boolean keepLocalFile) {
    File file = new File(path);

    State state = valid(file);
    String url = null;
    if (!state.isSuccess()) {
        return state;
    }
    try {
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(file));
        bos.write(data);
        bos.flush();
        bos.close();
        String newFileName = path.substring(0, path.lastIndexOf("/") + 1);
        url = new FtpUtils().uploadsUeFile(file, newFileName);
        if (!keepLocalFile) {
            file.delete();
        }
    } catch (IOException ioe) {
        return new BaseState(false, 4);
    }

    state = new BaseState(true, file.getAbsolutePath());
    state.putInfo("url", url);
    state.putInfo("size", data.length);
    state.putInfo("title", file.getName());
    return state;
}


實現效果



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