Springboot+wangEditor实现本地图片上传

由于通过百度搜索找不到比较完整正确的,故此将本人此次做的过程整理发出,有不对之处请指出。

与几个同学在一起做一个项目时,我处理关于文章发布的功能,通过百度找到了wangEditor,原因是其开源、简单易用

使用说明详见wangEditor使用手册

------------------------------------------------------------------------------------------------------------------------------------------------------------------

本人使用环境:jdk1.8、apache-maven-3.5.4、Eclipse jee-photon、spring-boot-1.5.2、apache-tomcat-8.0.23(用于模拟云服务器)

先看结果图

1、下载wangEditor富文本编辑器

2、只是使用wangEditor.js,注意在引入.js文件时路径的正确性

\wangEditor-3.1.0\release\wangEditor.js

3、创建webapp项目

配置文件-application.properties

// 访问端口号
server.port=8091
server.Context-path=/

// 视图前缀
spring.mvc.view.prefix=/WEB-INF/
// 视图后缀
spring.mvc.view.suffix=.jsp

比如上述配置访问http://localhost:8091/upload 

4、依赖(具体的就不粘贴了,只粘贴必要的)-pom.xml

	<!-- 父依赖 -->
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath />
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<scope>provided</scope>
		</dependency>

		<!--jstl依赖 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>

		<!--使jsp页面生效 -->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

5、页面- index.jsp

配置服务器端地址-后台代码的访问地址

editor.customConfig.uploadImgServer = '/test/upload'

自定义上传参数-接收名称(本人使用spring-boot,只需设置同名参数)

editor.customConfig.uploadFileName = 'imgFile'

<%@ 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>
<title>wangEditor 菜单和编辑器区域分离</title>
<style type="text/css">
.toolbar {
	border: 1px solid #ccc;
}

.text {
	border: 1px solid #ccc;
	height: 400px;
}
</style>
</head>
<body>

	<div id="div1" class="toolbar"></div>
	<div style="padding: 5px 0; color: #ccc">请在下方编辑区输入文章文章内容</div>
	<div id="div2" class="text">
		<!--可使用 min-height 实现编辑区域自动增加高度-->
	</div>

	<!-- 修改.js目录位置 -->
	<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
	<script type="text/javascript" src="../js/wangEditor.js"></script>
	<script type="text/javascript">
		var E = window.wangEditor
		var editor = new E('#div1', '#div2') // 两个参数也可以传入 elem 对象,class 选择器
		// editor.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
		// 配置服务器端地址
		editor.customConfig.uploadImgServer = '/test/upload'
		// 将图片大小限制为 3M
		editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
		// 自定义上传参数
		editor.customConfig.uploadFileName = 'imgFile'
		editor.customConfig.uploadImgHooks = {
			before : function(xhr, editor, files) {
				// 图片上传之前触发
				// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,files 是选择的图片文件

				// 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
				// return {
				//     prevent: true,
				//     msg: '放弃上传'
				// }
			},
			success : function(xhr, editor, result) {
				// 图片上传并返回结果,图片插入成功之后触发
				// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
			},
			fail : function(xhr, editor, result) {
				// 图片上传并返回结果,但图片插入错误时触发
				// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
			},
			error : function(xhr, editor) {
				// 图片上传出错时触发
				// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
			},
			timeout : function(xhr, editor) {
				// 图片上传超时时触发
				// xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
			},

			// 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
			// (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错)
			customInsert : function(insertImg, result, editor) {
				// 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
				// insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果

				// 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
				var url = result.url
				insertImg(url)

				// result 必须是一个 JSON 格式字符串!!!否则报错
			}
		}
       // 必须放到有关于编辑器设置前面
		editor.create()

	</script>
</body>
</html>

6、为了符合返回格式,目的是让存到服务器的图片回显到编辑器中-ImgInfo.java

作者文档有详细说明

上传图片的服务器端接口,接口返回的数据格式如下(实际返回数据时,不要加任何注释!!!

{

    // errno 即错误代码,0 表示没有错误。

    //       如果有错误,errno != 0,可通过下文中的监听函数 fail 拿到该错误码进行自定义处理

    "errno": 0,

 

    // data 是一个数组,返回若干图片的线上地址

    "data": [

        "图片1地址",

        "图片2地址",

        "……"

    ]}

public class ImgInfo {

	private Integer error;
	private String[] url;

	public Integer getError() {
		return error;
	}

	public void setError(Integer error) {
		this.error = error;
	}

	public String[] getUrl() {
		return url;
	}

	public void setUrl(String[] url) {
		this.url = url;
	}

	@Override
	public String toString() {
		return "ImgInfo [error=" + error + ", url=" + Arrays.toString(url) + "]";
	}

}

7、启动类-Starter.java

简要说明:

7.1 @RequestMapping("/upload")

表示访问时使用的最后面的名称(http://localhost:8091/upload

7.2 @RequestMapping("/test/upload")

表示前面提到的index.jsp中设置的服务器端地址

7.3 @ResponseBody

将JavaBean对象改为JSON格式返回给浏览器

JSON参考:https://www.cnblogs.com/qiankun-site/p/5774325.html

7.4 下面变量path与value是对应的,需要根据服务器的地址进行修改

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@SpringBootApplication
@Controller
public class Starter {
	public static void main(String[] args) {
		SpringApplication.run(Starter.class, args);
	}

	@RequestMapping("/upload")
	public String upload() {
		return "index";
	}

	@RequestMapping("/test/upload")
	@ResponseBody
	public ImgInfo setImgUrl(@RequestParam("imgFile") MultipartFile file, HttpServletResponse response)
			throws Exception {
		// Get the file and save it somewhere
		byte[] bytes = file.getBytes();
//        System.out.println(new String(bytes));
		String path = "D:\\tomcat\\apache-tomcat-8.0.23\\webapps\\test\\";
		File imgFile = new File(path);
		if (!imgFile.exists()) {
			imgFile.mkdirs();
		}
		String fileName = file.getOriginalFilename();// 文件名称
		System.out.println(path + fileName);

		try (FileOutputStream fos = new FileOutputStream(new File(path + fileName))) {
			int len = 0;
			fos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}

		String value = "http://localhost:8080/test/" + fileName;
		String[] values = { value };

		ImgInfo imgInfo = new ImgInfo();
		imgInfo.setError(0);
		imgInfo.setUrl(values);

		System.out.println(imgInfo.toString());
		return imgInfo;
	}

}

 

===================================感想========================================

只有在离开了别人的指导,通过种种资料实现自己未曾实现过的功能,才会感觉到自己的渺小。

猜你喜欢

转载自blog.csdn.net/m0_37461645/article/details/83384871