基于VSFTPD技术与KindEditor的简单案例

2020-07-27 10:20:21 浏览数 (1)

父工程

pom工程,实现项目所需jar包的版本控制

代码语言:javascript复制
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.bjsxt</groupId>
  <artifactId>parent</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
  
  	<!-- 对依赖的jar包的版本统一进行定义 -->
	<properties>
		<junit.version>4.12</junit.version>
		<spring.version>4.1.3.RELEASE</spring.version>
		<mybatis.version>3.2.8</mybatis.version>
		<mybatis.spring.version>1.2.2</mybatis.spring.version>
		<mysql.version>5.1.32</mysql.version>
		<slf4j.version>1.6.4</slf4j.version>
		<druid.version>1.0.9</druid.version>
		<jstl.version>1.2</jstl.version>
		<servlet-api.version>2.5</servlet-api.version>
		<tomcat.version>2.2</tomcat.version>
		<jsp-api.version>2.0</jsp-api.version>
		<zkClient-version>0.10</zkClient-version>
		<dubbo-version>2.5.4</dubbo-version>
		<jackson.version>2.4.2</jackson.version>
		<commons-net.version>3.3</commons-net.version>
		<commons-fileupload.version>1.3.1</commons-fileupload.version>
	</properties>
  	
  	<!-- jar包的依赖注入 ,由于该工程是一个父工程,所以jar包在该pom文件中只是声明 -->
	<dependencyManagement>
		<dependencies>
			<!-- 单元测试 -->
			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>${junit.version}</version>
			</dependency>
			<!-- 日志处理 -->
			<dependency>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-log4j12</artifactId>
				<version>${slf4j.version}</version>
			</dependency>
			<!-- Mybatis -->
			<dependency>
				<groupId>org.mybatis</groupId>
				<artifactId>mybatis</artifactId>
				<version>${mybatis.version}</version>
			</dependency>
			<dependency>
				<groupId>org.mybatis</groupId>
				<artifactId>mybatis-spring</artifactId>
				<version>${mybatis.spring.version}</version>
			</dependency>
			<!-- MySql -->
			<dependency>
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>${mysql.version}</version>
			</dependency>
			<!-- 连接池 -->
			<dependency>
				<groupId>com.alibaba</groupId>
				<artifactId>druid</artifactId>
				<version>${druid.version}</version>
			</dependency>
			<!-- Spring -->
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-beans</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-webmvc</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-jdbc</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-aspects</artifactId>
				<version>${spring.version}</version>
			</dependency>
			<!-- JSP相关 -->
			<dependency>
				<groupId>jstl</groupId>
				<artifactId>jstl</artifactId>
				<version>${jstl.version}</version>
			</dependency>
			<dependency>
				<groupId>javax.servlet</groupId>
				<artifactId>servlet-api</artifactId>
				<version>${servlet-api.version}</version>
				<scope>provided</scope>
			</dependency>
			<dependency>
				<groupId>javax.servlet</groupId>
				<artifactId>jsp-api</artifactId>
				<version>${jsp-api.version}</version>
				<scope>provided</scope>
			</dependency>
			<!-- 文件上传组件 -->
			<dependency>
				<groupId>commons-fileupload</groupId>
				<artifactId>commons-fileupload</artifactId>
				<version>${commons-fileupload.version}</version>
			</dependency>
			
			<dependency>
				<groupId>commons-net</groupId>
				<artifactId>commons-net</artifactId>
				<version>${commons-net.version}</version>
			</dependency>
			
			<!-- Jackson Json处理工具包 -->
			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-databind</artifactId>
				<version>${jackson.version}</version>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<!-- build适用于逻辑部署,例如热部署tomcat以及资源拷贝插件 -->
	<build>
		<resources>
			<resource>
				<directory>src/main/java</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
					<include>**/*.properties</include>
				</includes>
			</resource>
		</resources>
		<!-- tomcat插件,由于子项目不一定每个都是web项目,所以该插件只是声明,并未开启 -->
		<pluginManagement>
			<plugins>
				<!-- 配置Tomcat插件 -->
				<plugin>
					<groupId>org.apache.tomcat.maven</groupId>
					<artifactId>tomcat7-maven-plugin</artifactId>
					<version>${tomcat.version}</version>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
</project>

子工程

war工程,继承与父工程,实现具体的业务逻辑

子工程结构图

commons

三个工具类,实现文件的上传,名字的随机取名,将objec类型数据转换成json类型字符串

FtpUtil .java

代码语言:javascript复制
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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;

/**
 * ftp上传下载工具类
 */
public class FtpUtil {

	/** 
	 * Description: 向FTP服务器上传文件 
	 * @param host FTP服务器hostname 
	 * @param port FTP服务器端口 
	 * @param username FTP登录账号 
	 * @param password FTP登录密码 
	 * @param basePath FTP服务器基础目录
	 * @param filePath FTP服务器文件存放路径。例如分日期存放:/2018/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 
	 */  
	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;
	}
}

IDUtils .java

代码语言:javascript复制
import java.util.Random;
import java.util.UUID;

/**
 * 各种id生成策略
 * @version 1.0
 */
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("d", 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("d", end2);
		long id = new Long(str);
		return id;
	}
	
}

JsonUtils.java

代码语言:javascript复制
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON转换工具类
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
    
}

service层

接口以及实现类 实现图片的上传操作

PicUploadService .java

代码语言:javascript复制
import java.util.Map;

import org.springframework.web.multipart.MultipartFile;

public interface PicUploadService {
	Map<String,Object>fileUpload(MultipartFile filename);
}

PicUploadServiceImpl.java

代码语言:javascript复制
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.bjsxt.commons.FtpUtil;
import com.bjsxt.commons.IDUtils;
import com.bjsxt.service.PicUploadService;
/**
 * 图片上传Service
 * @author Administrator
 *
 */
@Service
public class PicUploadServiceImpl implements PicUploadService {
			//通过注解的形式将字符串注入到properties文件中
			@Value("${FTP_HOST}")
	        private String FTP_HOST;
			
			@Value("${FTP_PORT}")
	        private int FTP_PORT;
			
			@Value("${FTP_USERNAME}")
	        private String FTP_USERNAME;
			
			@Value("${FTP_PASSWORD}")
	        private String FTP_PASSWORD;
			
			@Value("${FTP_BASEPATH}")
	        private String FTP_BASEPATH;
			
			@Value("${HTTP_BASE_PATH}")
			private String HTTP_BASE_PATH;
	@Override
	public Map<String, Object> fileUpload(MultipartFile filename) {
		Map<String, Object> map = new HashMap<>();
		Date date = new Date();
		try {
		SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
		String path = sdf.format(date);
		System.out.println(path);
		String newFileName = IDUtils.genImageName() filename.getOriginalFilename().substring(filename.getOriginalFilename().lastIndexOf("."));
		System.out.println(newFileName);
		boolean flag = FtpUtil.uploadFile(this.FTP_HOST, this.FTP_PORT, this.FTP_USERNAME, this.FTP_PASSWORD, this.FTP_BASEPATH, path, newFileName, filename.getInputStream());
		System.out.println(flag);
		if(flag){
				map.put("error", 0);
				//http://192.168.179.128/yyyy/MM/dd/newFileName
				map.put("url", this.HTTP_BASE_PATH path newFileName);
			}else{
				map.put("error", 1);
				map.put("message","上传失败");
			}
		} catch (IOException e) {
			map.put("error", 1);
			map.put("message","上传失败");
			e.printStackTrace();
		}
		
		return map;
	}

}

控制层

实现页面交互

PageController

代码语言:javascript复制
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PageController {
	
	@RequestMapping("/")
	public String showPage() {
		
		return "index";
		
		
	}
}

PicUploadController

代码语言:javascript复制
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bjsxt.commons.JsonUtils;
import com.bjsxt.service.PicUploadService;

@Controller
@RequestMapping("/pic")
public class PicUploadController {
	
	@Autowired
	private PicUploadService picUploadService;
	
	/**
	 * 图片上传
	 * @param filename
	 * @return
	 * ftp://192.168.179.129/2019/07/23/1563849201122248.png
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public String fileUpload(MultipartFile filename) {
		
		Map<String, Object>map=this.picUploadService.fileUpload(filename);
		
		
		return JsonUtils.objectToJson(map);

	}
}

ContextSaveController

代码语言:javascript复制
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bjsxt.commons.JsonUtils;
//content/save
@Controller
@RequestMapping("/content")
public class ContextSaveController {

	/**
	 * 保存字符串和文本
	 */
	@RequestMapping(value="/save",produces=MediaType.APPLICATION_JSON_VALUE)
	public String Save(String desc) {
		
		System.out.println(desc);
		Map<String, Object>map=new HashMap<String, Object>();
		map.put("status",200);
		return JsonUtils.objectToJson(map);
		
	}
}

resources文件

存放srping相关配置文件,负责spingmvc的操作

applicationContext-service.xml

代码语言:javascript复制
<?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:p="http://www.springframework.org/schema/p"
	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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 扫描properties配置文件 -->
	<context:property-placeholder location="classpath:resource.properties"/>
	<!-- 扫描bean对象 -->
	<context:component-scan base-package="com.bjsxt.service"/>
</beans>

resource.properties

请根据自己虚拟机地址和端口以及用于ftp的用户名等进行书写

代码语言:javascript复制
FTP_HOST=192.168.179.129
FTP_PORT=21
FTP_USERNAME=ftpuser
FTP_PASSWORD=ftpuser
FTP_BASEPATH=/home/ftpuser
HTTP_BASE_PATH=http://192.168.179.129

springmvc.xml

代码语言:javascript复制
<?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:p="http://www.springframework.org/schema/p"
	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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
      <!-- 包的扫描器主要是扫描@controller -->
      <context:component-scan base-package="com.bjsxt.web.controller"/>  

	   <!-- 注册两个新对象 主要是为了来处理springmvc中的其他anntation 如:@requestmapping -->	
	   <mvc:annotation-driven/>
	   
	   <!-- 视图解析器 -->
	   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" /><!-- jsp所在的前缀 -->
		<property name="suffix" value=".jsp" />
    </bean>
     <!-- 文件上传处理器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<property name="defaultEncoding" value="utf-8"></property>
    	<property name="maxInMemorySize" value="1024"></property>
    	<!-- 单位字节 -->
    	<!-- org.springframework.web.multipart.MaxUploadSizeExceededException -->
    	<property name="maxUploadSize" value="1000000"></property>
    </bean>
    <!-- 配置静态资源映射 -->
    <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
	<mvc:resources location="/WEB-INF/js/" mapping="/js/**"/>
</beans>

KindEditor、jquery

这些资源请自行下载自行下载

前端代码

index.jsp

代码语言:javascript复制
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/js/kindeditor/kindeditor.js"></script>
<script type="text/javascript" src="/js/kindeditor/lang/zh_CN.js"></script>
<script type="text/javascript" src="/js/jquery-1.7.2.js"></script>
<script type="text/javascript">
	$(function(){
		var obj;
		KindEditor.ready(function(K) {
		   /* textarea的id  */
	       obj= K.create('#text_id', { 
	                uploadJson : 'https://img.yuanmabao.com/zijie/pic/upload',
	                filePostName:'filename',//因为是基于spring的所以ajax中的参数要和接口中定义的参数一致,特别是大小写,否则会报空指针异常
	                dir:"image"
	        });
	   });
		
		//给按钮添加点击事件
		$("#but").click(function(){
			//将KindEditor中的数据同步到textarea中
			obj.sync();
			
			//通过ajax方式提交表单      serialize()作用:将表单中的数据序列化为key=value&key=value.....
			$.post("/content/save",$("#myForm").serialize(),function(data){
				if(data.status == 200){
					alert("提交成功");
				}else{
					alert("提交失败");
				}
			});
		});
		
	});
</script>
</head>
<body>
<h1>1</h1>
	<form id="myForm">
	<textarea rows="20" cols="20" id="text_id" name="desc"></textarea>
	<input type="button" value="OK" id="but"/>
	</form>
</body>
</html>

web.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<!-- 上下文参数,告诉Spring配置文件路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext-*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 配置springmvc -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

运行效果

文件上传后,会打印图片的地址,只需要把http改成ftp访问即可,如下图

注意

要根据需要配置文件的内容来创建相应的包或者目录,或者在配置文件中自行修改

改进: 输入后直接自动同步内容到textarea标签内

1.创建图片上传的service,service实现类,controller(已实现) 2.下载KindEditor,放到静态资源中,并通过script标签指定(注意核实路径,js指定后需要重启项目)

代码语言:javascript复制
<script src="/static/js/kindeditor/kindeditor.js"></script>
<script src="/static/js/kindeditor/lang/zh-CN.js"></script>
<script src="https://cdn.bootcss.com/jquery/2.2.1/jquery.min.js"></script>

3.设置自动提交的代码

代码语言:javascript复制
	$(function(){	
		var obj;
		KindEditor.ready(function(K) {
	       obj= K.create('#analyse', { /* textarea的id值  */
	                uploadJson : 'https://img.yuanmabao.com/zijie/pic/upload',
	                filePostName:'filename',//因为是基于spring的所以ajax中的参数要和接口中定义的参数一致,特别是大小写,否则会报空指针异常
	                dir:"image",
	                syncType:"form",
	                afterCreate : function() { this.sync(); }, //自动提交, 关键是这两个
					afterBlur: function(){this.sync();}///自动提交,关键是这两个
	        });
	   });

    });
  1. 项目案例源码: 链接:https://pan.baidu.com/s/1DS2rEw0Z3OHT3GSqYaGSVA 提取码:kl8b

0 人点赞