使用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中配置静态资源放行

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

为了在Vue3中使用wangEditor富文本批量上传图片,你需要按照以下步骤进行操作: 1.首先,你需要安装wangEditor。你可以通过npm安装wangEditor,命令如下: ```shell npm install wangeditor --save ``` 2.在你的Vue组件中引入wangEditor,并在mounted钩子函数中初始化wangEditor。你需要在初始化时设置上传图片的配置,包括上传图片的路径和上传图片的处理函数。以下是一个示例: ```javascript <template> <div ref="editorElem" /> </template> <script> import wangEditor from 'wangeditor' export default { mounted() { const editor = new wangEditor(this.$refs.editorElem) // 配置上传图片的路径和处理函数 editor.customConfig.uploadImgServer = '/upload' editor.customConfig.uploadImgHooks = { before: function(xhr, editor, files) { // 在这里可以对上传图片进行处理 }, success: function(xhr, editor, result) { // 图片上传成功后的处理函数 }, fail: function(xhr, editor, result) { // 图片上传失败后的处理函数 }, error: function(xhr, editor) { // 图片上传出错的处理函数 }, timeout: function(xhr, editor) { // 图片上传超时的处理函数 }, customInsert: function(insertImg, result, editor) { // 在这里可以对插入的图片进行处理 insertImg(result.data) } } editor.create() } } </script> ``` 在上面的代码中,你需要将`/upload`替换为你的图片上传路径。在`uploadImgHooks`中,你可以设置上传图片的处理函数,包括上传前的处理函数、上传成功后的处理函数、上传失败后的处理函数、上传出错的处理函数、上传超时的处理函数和插入图片后的处理函数。在`customInsert`函数中,你可以对插入的图片进行处理。 3.在你的服务器端设置图片上传的处理函数。在上传图片的处理函数中,你需要将上传图片保存到服务器上,并返回一个JSON格式的数据,包括图片的URL和图片的宽度和高度。以下是一个示例: ```python import os from flask import Flask, request, jsonify from werkzeug.utils import secure_filename app = Flask(__name__) @app.route('/upload', methods=['POST']) def upload(): file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) url = 'http://example.com/uploads/' + filename return jsonify({ 'errno': 0, 'data': [url], }) ``` 在上面的代码中,你需要将`http://example.com/uploads/`替换为你的图片上传路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值