ssm + ftp +ueditor

5 篇文章 0 订阅
3 篇文章 0 订阅

目录结构

在这里插入图片描述

jar 包

ueditor.jar

mvn install:install-file -Dfile=ueditor-1.1.2.jar -Dpackaging=jar -DgroupId=com.baidu.ueditor -DartifactId=ueditor -Dversion=1.1.2
<!--
        ueditor
        mvn install:install-file -Dfile=ueditor-1.1.2.jar -Dpackaging=jar -DgroupId=com.baidu.ueditor -DartifactId=ueditor -Dversion=1.1.2
         -->
        <dependency>
            <groupId>com.baidu.ueditor</groupId>
            <artifactId>ueditor</artifactId>
            <version>1.1.2</version>
        </dependency>

json.jar
直接放到WEB-INF/lib目录下

spring mvc 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <!-- TODO 添加 接口包的扫描 -->
    <!-- Spring容器中注册@controller注解的Bean -->
    <context:component-scan base-package="com.laolang.jd.modules.*.web" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


    <!-- 注解驱动 -->
    <mvc:annotation-driven />

    <!-- 静态资源过虑 -->
    <mvc:default-servlet-handler/>

    <mvc:resources mapping="/favicon.ico" location="favicon.ico"/>


    <!-- ueditor  -->
    <mvc:view-controller path="/ueditorconfig" view-name="../../assets/ueditor/jsp/controller"/>

    <!-- jsp 视图  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>



    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600" />
        <property name="maxInMemorySize" value="4096" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

</beans>

ssm 图片上传

工具类

IDUtils

package com.laolang.jd.common.util;

import java.util.Random;

/**
 * 各种id生成策略
 * <p>Title: IDUtils</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p>
 *
 * @version 1.0
 * @author 入云龙
 * @date 2015年7月22日下午2:32:10
 */
public class IDUtils {

    /**
     * 图片名生成
     */
    public static String genImageName() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //long millis = System.nanoTime();
        //加上三位随机数
        Random random = new Random();
        int end3 = random.nextInt(999);
        //如果不足三位前面补0
        String str = millis + String.format("%03d", end3);

        return str;
    }

    /**
     * 商品id生成
     */
    public static long genItemId() {
        //取当前时间的长整形值包含毫秒
        long millis = System.currentTimeMillis();
        //long millis = System.nanoTime();
        //加上两位随机数
        Random random = new Random();
        int end2 = random.nextInt(99);
        //如果不足两位前面补0
        String str = millis + String.format("%02d", end2);
        long id = new Long(str);
        return id;
    }


}


FtpUtil

package com.laolang.jd.common.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;

/**
 * ftp上传下载工具类
 * <p>Title: FtpUtil</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p>
 *
 * @version 1.0
 * @author 入云龙
 * @date 2015年7月29日下午8:11:51
 */
public class FtpUtil {

    /**
     * Description: 向FTP服务器上传文件
     *
     * @param host     FTP服务器hostname
     * @param port     FTP服务器端口
     * @param username FTP登录账号
     * @param password FTP登录密码
     * @param basePath FTP服务器基础目录
     * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
     * @param filename 上传到FTP服务器上的文件名
     * @param input    输入流
     * @return 成功返回true,否则返回false
     */
    public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                     String filePath, String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);// 连接FTP服务器
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            //切换到上传目录
            if (!ftp.changeWorkingDirectory(basePath + filePath)) {
                //如果目录不存在创建目录
                String[] dirs = filePath.split("/");
                String tempPath = basePath;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            return result;
                        } else {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }
            //设置上传文件的类型为二进制类型
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            //上传文件
            if (!ftp.storeFile(filename, input)) {
                return result;
            }
            input.close();
            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * Description: 从FTP服务器下载文件
     *
     * @param host       FTP服务器hostname
     * @param port       FTP服务器端口
     * @param username   FTP登录账号
     * @param password   FTP登录密码
     * @param remotePath FTP服务器上的相对路径
     * @param fileName   要下载的文件名
     * @param localPath  下载后保存到本地的路径
     * @return 成功返回true,否则返回false
     */
    public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                       String fileName, String localPath) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(host, port);
            // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
            ftp.login(username, password);// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(fileName)) {
                    File localFile = new File(localPath + "/" + ff.getName());

                    OutputStream is = new FileOutputStream(localFile);
                    ftp.retrieveFile(ff.getName(), is);
                    is.close();
                }
            }

            ftp.logout();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }
}

ftp 配置文件

GlobalConfig .java

package com.laolang.jd.core.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 全局配置
 *
 * @author laolang
 * @version 1.0
 * 2019/1/5 17:36
 */
@Component
public class GlobalConfig {

    @Value("${sys.author}")
    private String sysAuthor;

    @Value("${ftp.address}")
    private String ftpAddress;

    @Value("${ftp.port}")
    private Integer ftpPort;

    @Value("${ftp.userName}")
    private String ftpUserName;

    @Value("${ftp.passWord}")
    private String ftpPassWord;

    @Value("${ftp.basePath}")
    private String ftpBasePath;

    @Value("${ftp.imageBasePath}")
    private String ftpImageBasePath;

    public String getFtpAddress() {
        return ftpAddress;
    }

    public void setFtpAddress(String ftpAddress) {
        this.ftpAddress = ftpAddress;
    }

    public Integer getFtpPort() {
        return ftpPort;
    }

    public void setFtpPort(Integer ftpPort) {
        this.ftpPort = ftpPort;
    }

    public String getFtpUserName() {
        return ftpUserName;
    }

    public void setFtpUserName(String ftpUserName) {
        this.ftpUserName = ftpUserName;
    }

    public String getFtpPassWord() {
        return ftpPassWord;
    }

    public void setFtpPassWord(String ftpPassWord) {
        this.ftpPassWord = ftpPassWord;
    }

    public String getFtpBasePath() {
        return ftpBasePath;
    }

    public void setFtpBasePath(String ftpBasePath) {
        this.ftpBasePath = ftpBasePath;
    }

    public String getFtpImageBasePath() {
        return ftpImageBasePath;
    }

    public void setFtpImageBasePath(String ftpImageBasePath) {
        this.ftpImageBasePath = ftpImageBasePath;
    }

    public String getSysAuthor() {
        return sysAuthor;
    }

    public void setSysAuthor(String sysAuthor) {
        this.sysAuthor = sysAuthor;
    }
}


# 系统配置
sys.author=khl
sys.adminPath=/admin

cache.redis.host=127.0.0.1
cache.redis.port=6379

#ftp 配置
ftp.address=127.0.0.1
ftp.port=21
ftp.userName=jdhello
ftp.passWord=jdhello
ftp.basePath=/upload
ftp.imageBasePath=http://image.jdhello.com/upload

service

PicUploadService

package com.laolang.jd.modules.admin.service;

import com.laolang.jd.common.util.FtpUtil;
import com.laolang.jd.common.util.IDUtils;
import com.laolang.jd.core.config.GlobalConfig;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传服务
 *
 * @author laolang
 * @version 1.0
 * 2019/1/8 02:18
 */
@Service
public class PicUploadService {

    @Autowired
    private GlobalConfig globalConfig;

    public String uploadPic(MultipartFile multipartFile) {
        if (null == multipartFile || multipartFile.isEmpty()) {
            return null;
        }

        String originalFilename = multipartFile.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));

        String imageName = IDUtils.genImageName();

        DateTime dateTime = new DateTime();
        String filePath = dateTime.toString("/yyyy/MM/dd");
        try {
            FtpUtil.uploadFile(globalConfig.getFtpAddress(),globalConfig.getFtpPort(),globalConfig.getFtpUserName(),globalConfig.getFtpPassWord(),
                    globalConfig.getFtpBasePath(),filePath,imageName+ext,multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


        return globalConfig.getFtpImageBasePath() + filePath + "/" + imageName + ext;
    }
}

Controller

package com.laolang.jd.modules.admin.web;

import com.laolang.jd.common.json.PrintJsonWriter;
import com.laolang.jd.common.json.SimpleAjax;
import com.laolang.jd.common.util.GsonUtil;
import com.laolang.jd.common.util.StringUtils;
import com.laolang.jd.modules.admin.service.PicUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * ftp
 *
 * @author laolang
 * @version 1.0
 * 2019/1/8 02:22
 */
@RequestMapping("/admin/ftp")
@Controller
public class AdminFtpController {

    @Autowired
    private PicUploadService picUploadService;

    /**
     * ueditor 图片上传
     * @param multipartFile
     * @param response
     */
    @RequestMapping(value = "/ueditorupload",method = RequestMethod.POST)
    public void ueditorUpload(@RequestParam("file") MultipartFile multipartFile , HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        try {
            String url = picUploadService.uploadPic(multipartFile);

            if(StringUtils.isNotBlank(url)){
                map.put("state", "SUCCESS");// UEDITOR的规则:不为SUCCESS则显示state的内容
                map.put("url",url);         //能访问到你现在图片的路径
                map.put("title","");
                map.put("original","realName" );

            }else{
                map.put("state", "文件上传失败!");
                map.put("url","");
                map.put("title", "");
                map.put("original", "");
            }

            String json = GsonUtil.toJson(map);

            PrintJsonWriter.printJson(response,json);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

ueditor 配置

config.json

/* 前后端通信相关的配置,注释只允许使用多行方式 */
{
    /* 上传图片配置项 */
    "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
    "imageFieldName": "file", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "", /* 图片访问路径前缀 */
    "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": "", /* 图片访问路径前缀 */
    "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": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "videoUrlPrefix": "", /* 视频访问路径前缀 */
    "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"
    ] /* 列出的文件类型 */

}

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/WEB-INF/jsp/common/common.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>jd 后台管理</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

 </head>
<body>

<script id="ueditor" name="content" type="text/plain"></script>
	




<!-- jQuery 2.2.3 -->
<script src="${ctx}/assets/adminlteiframe/plugins/jQuery/jquery-2.2.3.min.js"></script>
<!-- layui -->
<script src="${ctx}/assets/layui-2.4.5/layui.js"></script>
<!-- ztree -->
<script type="text/javascript" src="${ctx}/assets/zTree_v3-3.5.37/js/jquery.ztree.all.js"></script>
<!-- ueditor -->
<script type="text/javascript" src="${ctx}/assets/ueditor/ueditor.config.js"></script>
<!-- ueditor -->
<script type="text/javascript" src="${ctx}/assets/ueditor/ueditor.all.js"></script>
<!-- jd -->
<script src="${ctx}/assets/js/jd.js"></script>


<script src="${ctx}/assets/js/modules/admin/goodslist.js"></script>
</body>
</html>

js

        // ueditor

        UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
        UE.Editor.prototype.getActionUrl = function (action) {
            if ('uploadimage' === action || 'uploadscrawl' === action || 'uploadvideo' === action) {
                return jd.getBaseUrl() + '/admin/ftp/ueditorupload';
            } else {
                return this._bkGetActionUrl.call(this, action);
            }
        };

        var ue = UE.getEditor('ueditor', {
            serverUrl: jd.getBaseUrl() + '/ueditorconfig'
            // imageActionName : jd.getBaseUrl() + '/admin/ftp/upload'
        });

jd.getBaseUrl

            /**
             * 获取 basePath
             * 如:http://localhost:8080
             * @returns {string}
             */
            getBaseUrl() {
                // document.location.host   //表示当前域名 + 端口号
                // document.location.hostname  //表示域名
                // document.location.href   //表示完整的URL
                // document.location.port   //表示端口号
                // document.location.protocol   //表示当前的网络协议
                return document.location.protocol + '//' + document.location.host;

            }

注意事项

访问配置文件

  1. spring mvc 配置文件第27行
    由于mvc拦截了所有的请求,所以ueditor的controller.jsp无法访问,添加如下配置是为了访问到ueditor的controller.jsp
    <!-- ueditor  -->
    <mvc:view-controller path="/ueditorconfig" view-name="../../assets/ueditor/jsp/controller"/>
  1. js 第13行
    指定访问配置时的路径

config.json

第5行,指定 了图片表单名称,也就是:
在这里插入图片描述

ueditor js 引入顺序不能改变

···

···

done

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值