Skip to content

Commit

Permalink
实现editormd粘贴图片功能
Browse files Browse the repository at this point in the history
  • Loading branch information
aim467 committed Jul 24, 2021
1 parent 713fa56 commit 64fed88
Show file tree
Hide file tree
Showing 5 changed files with 199 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,26 @@
import com.root2z.service.ArticleService;
import com.root2z.service.CategoryService;
import com.root2z.service.TagService;
import com.root2z.utils.AliyunOSSUtil;
import com.root2z.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminArticleController {

@Resource private AliyunOSSUtil aliyunOSSUtil;

private final Logger logger = LoggerFactory.getLogger(AdminArticleController.class);

private final CategoryService categoryService;
Expand Down Expand Up @@ -145,4 +150,15 @@ public ResultVO changeStatus(
}
return ResultUtil.error("更改文章状态失败!", null);
}

@RequestMapping(value = "/article/upload", method = RequestMethod.POST)
@ResponseBody
public ResultVO MarkdownUploadImage(@RequestParam("editormd-image-file") MultipartFile file) {
String url = aliyunOSSUtil.uploadFile(file, "");
if (url != null) {
return ResultUtil.success("图片上传成功", url);
} else {
return ResultUtil.error("图片上传失败", null);
}
}
}
1 change: 0 additions & 1 deletion src/main/java/com/root2z/utils/AliyunOSSUtil.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.root2z.utils;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
Expand Down
18 changes: 5 additions & 13 deletions src/main/java/com/root2z/utils/FileUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,12 @@
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class FileUtils {

/**
* @param file 文件
* @param fileName 保存的文件名
* @return
*/
public static String upload(MultipartFile file, String fileName) {

Expand All @@ -35,10 +33,7 @@ public static String upload(MultipartFile file, String fileName) {
// 保存文件
file.transferTo(dest);
return randomFileName;
} catch (IllegalStateException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
return "";
}
Expand All @@ -47,22 +42,19 @@ public static String upload(MultipartFile file, String fileName) {
/**
* 生成随机文件名
*
* @return
* @param fileName 文件名
*/
public static String getRandomFileName(String fileName) {

// 获取后缀
String suffixName = fileName.substring(fileName.lastIndexOf("."));

SimpleDateFormat simpleDateFormat;
simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
// 获得当前时间
String datetime = simpleDateFormat.format(date);
Random random = new Random();
// 提取时间
int randNum = (int) (random.nextDouble() * (9999 - 1000 + 1)) + 10000;

String finaName = randNum + datetime + suffixName;

return finaName;
return randNum + datetime + suffixName;
}
}
93 changes: 92 additions & 1 deletion src/main/resources/templates/admin/article/add.html
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,103 @@ <h3>新增博客</h3>
tex: true, // 开启数学公式
flowChart: true, // 开启流程图支持
sequenceDiagram: true, // 开启时序图支持
saveHTMLToTextarea: true // 保存HTML到textarea
saveHTMLToTextarea: true, // 保存HTML到textarea
imageUpload: true,
imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL: contextPath + "/admin/article/upload",
onload: function () {
initPasteDragImg(this);
}
});
// 固定工具栏
contentEditor.setToolbarAutoFixed(true);
});

/**
* 初始化粘贴图片函数
* @param Editor
*/
function initPasteDragImg(Editor) {
let doc = document.getElementById(Editor.id);
doc.addEventListener('paste', function (event) {
let items = (event.clipboardData || window.clipboardData).items;
let file = null;
if (items && items.length) {
// 搜索剪切板items
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile();
break;
}
}
} else {
Swal.fire({
title: "当前浏览器不支持",
icon: "error"
})
return;
}
if (!file) {
Swal.fire({
title: "粘贴内容非图片",
icon: "error"
});
return;
}
uploadImg(file, Editor);
});
let dashboard = document.getElementById(Editor.id);
dashboard.addEventListener("dragover", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("dragenter", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("drop", function (e) {
e.preventDefault()
e.stopPropagation()
let files = this.files || e.dataTransfer.files;
uploadImg(files[0], Editor);
})
}

function uploadImg(file, Editor) {
let formData = new FormData();
let fileName = new Date().getTime() + "." + file.name.split(".").pop();
formData.append('editormd-image-file', file, fileName);
$.ajax({
url: Editor.settings.imageUploadURL,
type: 'post',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (data) {
let code = data.code
if (200 === code) {
Swal.fire({
title: data.message,
icon: "success"
})
let url = data.data
console.log(data);
if (/\.(png|jpg|jpeg|gif|bmp|ico)$/.test(url)) {
Editor.insertValue("![](" + url + ")");
} else {
Editor.insertValue("[下载附件](" + url + ")");
}
} else {
Swal.fire({
title: data.message,
icon: "error"
})
}
}
});
}

$('#addArticle').click(function () {
let article = document.getElementById("newArticle");
let formData = new FormData(article);
Expand Down
87 changes: 86 additions & 1 deletion src/main/resources/templates/admin/article/edit.html
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,97 @@ <h3>编辑文章</h3>
tex: true, // 开启数学公式
flowChart: true, // 开启流程图支持
sequenceDiagram: true, // 开启时序图支持
saveHTMLToTextarea: true // 保存HTML到textarea
saveHTMLToTextarea: true, // 保存HTML到textarea
imageUpload: true,
imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL: contextPath + "/admin/article/upload",
onload: function () {
initPasteDragImg(this);
}
});
// 固定工具栏
contentEditor.setToolbarAutoFixed(true);
});

/**
* 初始化粘贴图片函数
* @param Editor
*/
function initPasteDragImg(Editor) {
let doc = document.getElementById(Editor.id);
doc.addEventListener('paste', function (event) {
let items = (event.clipboardData || window.clipboardData).items;
let file = null;
if (items && items.length) {
// 搜索剪切板items
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile();
break;
}
}
} else {
console.log("当前浏览器不支持");
return;
}
if (!file) {
console.log("粘贴内容非图片");
return;
}
uploadImg(file, Editor);
});
var dashboard = document.getElementById(Editor.id)
dashboard.addEventListener("dragover", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("dragenter", function (e) {
e.preventDefault()
e.stopPropagation()
})
dashboard.addEventListener("drop", function (e) {
e.preventDefault()
e.stopPropagation()
var files = this.files || e.dataTransfer.files;
uploadImg(files[0], Editor);
})
}

function uploadImg(file, Editor) {
let formData = new FormData();
let fileName = new Date().getTime() + "." + file.name.split(".").pop();
formData.append('editormd-image-file', file, fileName);
$.ajax({
url: Editor.settings.imageUploadURL,
type: 'post',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (data) {
let code = data.code
if (200 === code) {
Swal.fire({
title: data.message,
icon: "success"
})
let url = data.data
console.log(data);
if (/\.(png|jpg|jpeg|gif|bmp|ico)$/.test(url)) {
Editor.insertValue("![](" + url + ")");
} else {
Editor.insertValue("[下载附件](" + url + ")");
}
} else {
Swal.fire({
title: data.message,
icon: "error"
})
}
}
});
}

$('#saveArticle').click(function () {
let article = document.getElementById("editArticle");
let formData = new FormData(article);
Expand Down

0 comments on commit 64fed88

Please sign in to comment.