使用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.引入wangEditorjscs

<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下面。cssjs放到webapp下面,在spring-mvc.xml中配置静态资源放行

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

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

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

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


相关推荐

  • datax(8):TaskGroupContainer源码解读

    datax(8):TaskGroupContainer源码解读继续深挖datax里的container,任务一个任务进入datax都会判断是jobContainer还是TaskGroupContainer。那后者要做哪些事情。一,TaskGroupContainer概述JobContainer将所有的task分配到TaskGroup中执行,TaskGroup启动5个线程去消费所有的taskTaskGroupContainer里的主入口为start方法,实现自AbstractContainer.startTaskGroupContainer.start.

    2022年5月17日
    41
  • 常用的算法和数据结构 面试_数据结构与算法面试题80道

    常用的算法和数据结构 面试_数据结构与算法面试题80道(1)红黑树的了解(平衡树,二叉搜索树),使用场景把数据结构上几种树集中的讨论一下:1.AVLtree定义:最先发明的自平衡二叉查找树。在AVL树中任何节点的两个子树的高度最大差别为一,所以它也被称为高度平衡树。查找、插入和删除在平均和最坏情况下都是O(logn)。增加和删除可能需要通过一次或多次树旋转来重新平衡这个树。节点的平衡因子是它的左子树的高度减去它的右子树的高度(有时相反)。…

    2022年8月18日
    3
  • virus.win32.parite.H查杀病毒的方法

    virus.win32.parite.H查杀病毒的方法virus.win32.parite.H病毒的查杀方法昨天电脑中了virus.win32.parite.H病毒,搞了2个多小时最终搞定了。以下记录下我的解决方法。第一步:下载Win32.Parite病毒专杀工具下载地址:http://download.csdn.net/detail/wuxiaokaixinguo/6333233第二步…

    2022年7月25日
    7
  • 剑指Offer算法题

    剑指Offer算法题

    2022年3月13日
    31
  • cmdping命令_cmd ping端口命令

    cmdping命令_cmd ping端口命令标题cmd-ping命令一、ping命令:通过发送Internet控制消息协议(ICMP)回响请求消息来验证与另一台TCP/IP计算机的IP级连接。相应的回响应答消息的接收情况将和往返过程的时间一起显示出来。Ping是用于检测网络连接性、可到达性和名称解析的疑难问题的主要TCP/IP命令。如果不带参数,ping将显示帮助。(ping-PacketInternet…

    2022年9月23日
    0
  • 提取pfx证书密钥对

    提取pfx证书密钥对两个测试证书test.pfx和test.cer.其中pfx证书包含RSA的公钥和密钥;cer证书用于提取pfx证书中密钥时允许当前电脑进行合法操作提取步骤如下:点击test.cer,安装cer证书2.从pfx提取密钥信息,并转换为key格式(pfx使用pkcs12模式补足)(1)提取密钥对opensslpkcs12-intest.pfx-nocerts-nodes-outtest.key//如果pfx证书已加密,会提示输入密码。如果cer证书没有安装

    2022年5月31日
    54

发表回复

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

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