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

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

wangEditor文档

环境搭建

  • 使用wangEditor
  • SpringMVC

1.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.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

<?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

<?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.引入wangEditor 的js 和cs

<link rel="stylesheet" href="/static/css/wangEditor.min.css" />
<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

<%@ 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层

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格式要遵循一下格式

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

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

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

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • datagrip激活码_最新在线免费激活[通俗易懂]

    (datagrip激活码)JetBrains旗下有多款编译器工具(如:IntelliJ、WebStorm、PyCharm等)在各编程领域几乎都占据了垄断地位。建立在开源IntelliJ平台之上,过去15年以来,JetBrains一直在不断发展和完善这个平台。这个平台可以针对您的开发工作流进行微调并且能够提供…

    2022年3月28日
  • dump文件在线分析_hprof文件分析工具

    dump文件在线分析_hprof文件分析工具阿里P8教你如何使用Jprofile解析dump文件-知乎支持macM1

    2022年10月2日
  • VS2012 产品密钥「建议收藏」

    VS2012 产品密钥「建议收藏」vs2012产品激活码,序列号,旗舰版(utimate)YKCW6-BPFPF-BT8C9-7DCTH-QXGWC

    2022年10月15日
  • 服务器永恒之蓝病毒解决方法_永恒之蓝病毒作者

    服务器永恒之蓝病毒解决方法_永恒之蓝病毒作者一、NSA“永恒之蓝”勒索蠕虫全球爆发2017年5月12日爆发的WannaCry勒索病毒肆虐了全球网络系统,引起各国企业和机构极大恐慌。而这次受害最严重的是Windows系统,自然也被锁定为怀疑对象,有人认为正是因为该系统对于漏洞的麻木和疏漏才导致了此次勒索病毒的蔓延。作为受害者的微软却将矛头指向美国国安局(NSA)和永恒之蓝。不法分子利用…

    2022年10月16日
  • 游戏数据实时监控和分析[通俗易懂]

    游戏数据实时监控和分析[通俗易懂]概述为了更好的了解到游戏运行时的状态,对相关的功能和数据进行分析是很重要的,设计了本系统。现有的游戏数据大部分采用的是文本输出,备份,然后离线数据分析的方式,不能实时的监控的游戏的状态.相关技术:1:产生日志服务器采用c++实现2:日志监控服务器采用Java实现3:采用hadloop分布式架构.为应付大规模数据和实时的要求,尽快对数据进行分析4:存储日志采用mo

    2022年5月12日
  • css 去掉超链接样式「建议收藏」

    css 去掉超链接样式「建议收藏」我们可以用CSS语法来控制超链接的形式、颜色变化,为什么链接一定要使用下划线和颜色区分呢?其主要原因主要是考虑到1、视力差的人2、色盲的人。。。下面我们做一个这样的链接:未被点击时超链接文字无下划线,显示为蓝色;当鼠标在链接上时有下划线,链接文字显示为红色;当点击链接后,链接无下划线,显示为绿色。实现方法很简单,在源代码的和之间加上如下的CSS语法控制: …

    2022年7月19日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号