1. 程式人生 > >Springboot+wangEditor實現本地圖片上傳

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;
	}

}

 

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

只有在離開了別人的指導,通過種種資料實現自己未曾實現過的功能,才會感覺到自己的渺小。