使用wangEditor批量上传并且保证图片顺序

2022-06-30 10:39:21 浏览数 (1)

wangEditor文档

环境搭建

  • 使用wangEditor
  • SpringMVC

1.pom.xml

代码语言:javascript复制
<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.itmayiedu</groupId>
	<artifactId>WangEditorDemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- 文件上传 -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.2</version>
		</dependency>

		<!-- Spring 依赖(context包含:beans/core/aop/expression) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.17.RELEASE</version>
		</dependency>

		<!--SpringMVC依赖(springwebmvc包含了:beans/core/aop/expression/context) -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.17.RELEASE</version>
		</dependency>

		<!-- jackjson start -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.7.4</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.7.4</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.7.4</version>
		</dependency>
		<!-- jackjson end -->
	</dependencies>
	<build>
		<plugins>
			<!-- 制定jdk版本 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- war 包类型的时候 mvn package 的时候需要安装maven插件 -->
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<!-- tomcat7 maven插件 -->
			<plugin>
				<groupId>org.apache.tomcat.maven</groupId>
				<artifactId>tomcat7-maven-plugin</artifactId>
				<version>2.2</version>

				<configuration>
					<!--项目访问路径。当前配置的访问是localhost:9090/, 如果配置是/aa,则访问路径为localhost:9090/aa -->
					<path>/</path>
					<port>8080</port>
					<uriEncoding>UTF-8</uriEncoding><!-- 非必需项 -->
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

使用maven-tomcat插件,运行使用clean tomcat7:run命令

2.web.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">
  
	<!-- 字符集处理 -->
	<filter>
		<filter-name>encodingFilter</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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<!--过滤器拦截所有 -->
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- spring mvc 核心控制器DispatcherServlet组件 -->
	<servlet>
		<servlet-name>springServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath*:/spring-mvc*.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

3.spring-mvc.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: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">
 
	<!-- 使用 Annotation 自动注册 Bean,只扫描 @Controller -->
	<context:component-scan base-package="com.itmayiedu.web.controller"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- 默认的注解映射的支持 -->
	<mvc:annotation-driven />

	<!-- 上传文件拦截,设置最大上传文件大小 10M = 10*1024*1024(B) = 10485760 bytes -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="10485760" />
	</bean>

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

	<!-- 静态资源映射 -->
	<mvc:resources mapping="/static/**" location="/static/"
		cache-period="31536000" />
</beans>

4.引入wangEditorjscs

代码语言:javascript复制
<link rel="stylesheet" href="/static/css/wangEditor.min.css" />
代码语言:javascript复制
<script type="text/javascript" src="/static/js/wangEditor.min.js"></script>
<script type="text/javascript" src="/static/js/jQuery-3.4.1.js"></script>

使用wangEditor批量上传并且保证上传图片顺序

1.upload.js

代码语言: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>富文本编辑器批量上传图片</title>
<link rel="stylesheet" href="/static/css/wangEditor.min.css" />
</head>
<body>
	<div id="editor"></div>
	<script type="text/javascript" src="/static/js/wangEditor.min.js"></script>
	<script type="text/javascript" src="/static/js/jQuery-3.4.1.js"></script>
	<script>
		$(function() {
			var E = window.wangEditor;
			var editor = new E(document.getElementById('editor'));
			//自定义文件上传
			editor.customConfig.customUploadImg = function(files, insert) {
				var daw = new FormData();
				for (var i = 0; i < files.length; i  ) {
					daw.append("files", files[i]);
				}
		//发送异步请求
				$.ajax({
					url : "${pageContext.request.contextPath}/uploadImage",
					type : "POST",
					data : daw,
					async : false,
					cache : false,
					contentType : false,
					processData : false,
					success : function(da) {
						 
						if (da.errno == 0) {
							for (var j = 0; j < da.data.length; j  ) {
								insert(da.data[j]);
							}
						} else {
							alert(da.msg);
							return;
						}
					},
				});
			}
			editor.create()
		});
	</script>
</body>
</html>

2.contorller层

代码语言:javascript复制
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class UploadController {

	private static final String UPLOAD_IMAGE = "/static/upload/image";

	/**
	 * 跳转到富文本编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload() {
		return "upload";
	}

	/**
	 * 上传图片
	 */
	@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadImage(@RequestParam(value = "files", required = false) List<MultipartFile> files,
			HttpServletRequest request) {
		System.out.println(">>>>>"   files);
		Map<String, Object> result = new HashMap<>();
		String imgUrls[] = new String[files.size()];

		// 文件存放的路径
		String filePath = request.getSession().getServletContext().getRealPath(UPLOAD_IMAGE);
		System.out.println(filePath);

		if (files != null && files.size() > 0) {
			for (int i = 0; i < files.size(); i  ) {
				MultipartFile multipartFile = files.get(i);
				// System.out.println(String.format("文件名称:%s",multipartFile.getOriginalFilename()));
				String fileName = multipartFile.getOriginalFilename();
				String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
				// System.out.println(String.format("后缀名:%s", fileSuffix));
				fileName = UUID.randomUUID().toString().replace("-", "")   fileSuffix;
				// System.out.println(fileName);

				// 判断路径是否存在,不存在则创建文件夹
				File file = new File(filePath);
				if (!file.exists()) {
					file.mkdir();
				}

				// 将文件写入目标
				file = new File(filePath, fileName);
				try {
					multipartFile.transferTo(file);
				} catch (IOException e) {
					e.printStackTrace();
				}

				// 获取服务端路径 ,为了图片显示
				String serverPath = String.format("%s://%s:%s%s%s", request.getScheme(), request.getServerName(),
						request.getServerPort(), request.getContextPath(), UPLOAD_IMAGE);
				;
				 
				imgUrls[i]=serverPath "/" fileName;
				System.out.println(imgUrls[i]);
			}

		}

		result.put("errno", 0);
		result.put("data", imgUrls);
		return result;
	}

}

可以把文件上传封装成一个工具类。我这里就没有进行封装了。返回的json格式要遵循一下格式

代码语言:javascript复制
{
    // errno 即错误代码,0 表示没有错误。
    //      如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理
    "errno": 0,

    // data 是一个数组,返回若干图片的线上地址
    "data": [
        "图片1地址",
        "图片2地址",
        "……"
    ]
}
//参考wangEditor中的上传图片文档

SpringMVC 页面跳转是通过controller进行跳转,我们把页面放到WEB-INF下面。cssjs放到webapp下面,在spring-mvc.xml中配置静态资源放行

还没有测试再网络延迟下批量上传图片是否保证图片顺序

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/100784.html原文链接:https://javaforall.cn

0 人点赞