1、vue中:
1.1、安装 mavon-editor
npm install mavon-editor --save
1.2、配置 mavon-editor
main.js 中添加
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
Vue.use(mavonEditor)
1.3、组件中使用
(1)调用组件
<mavon-editor :ishljs = "true" v-model="value" ref=md @save="save" @imgAdd="imgAdd" />
<!--
@imgAdd="imgAdd":监听图片上传事件
@save=“save”:监听图片保存事件
value:整个markdown文件的内容
-->
(2)添加 save() 和 imgAdd()
axios的封装:
let base = 'http://localhost:9090'; //后台服务器的请求地址
export const postRequest=(url, params)=>{
return axios({
method: 'post',
url: `${base}${url}`,
data: params
})
}
在要使用mavon-editor的组件的methods中添加 save() 和 imgAdd() :
methods: {
//保存md到后台
save(){
//传递name(文件名),typeId(文件所属类别),value(md文件内容)
var params = {}
params.name = this.name
params.typeId = this.id
params.content = this.editForm.content
this.postRequest("/saveMd",params).then(res => {
console.log(res)
})
},
//保存图片到后台
imgAdd(pos, $file){
var _this = this;
// 第一步.将图片上传到服务器.
var formdata = new FormData();
formdata.append('image', $file);
this.postRequest('/uploadFile',formdata).then(res => {
console.log('res:'+res)
var url = res //取出上传成功后的url
console.log('pos:'+pos)
_this.$refs.md.$img2Url(pos, url)
})
},
}
2、springboot中:
2.1、配置上传路径映射
application.yml 中添加配置
#文件上传路径
file:
upload:
abpath: F:/note/
urlpath: /note/**
mdImageDir: /note/assets/
2.2、添加路径映射
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyWebAppConfig implements WebMvcConfigurer {
//文件夹绝对路径
@Value("${file.upload.abpath}")
private String abpath;
//文件夹url
@Value("${file.upload.urlpath}")
private String ulrpath;
public MyWebAppConfig() {
System.out.println("注册进来了=====================");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(ulrpath).addResourceLocations("file:"+abpath);
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
}
}
2.3、添加controller层
import com.alibaba.fastjson.JSONObject;
import com.xlblog.blog.utils.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
@RestController
public class ArticleController {
//上传目录绝对路径
@Value("${file.upload.abpath}")
private String abpath;
//上传目录url
@Value("${file.upload.mdImageDir}")
private String mdImageDir;
//端口号
@Value("${server.port}")
private String port;
//上传md文件
@RequestMapping("/saveMd")
//注意参数传递是以json格式,因此用@RequestBody定义接收参数
public String saveMd(@RequestBody JSONObject param){
//取出java中对应参数的值
String str = param.getString("content");
String name=param.getString("name");
String typeId=param.getString("typeId");
//文件保存路径 F:\note\555.md
String filepath=abpath+name+".md";
FileUtil.string2File(str,filepath);
return "ok";
}
//上传图片
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("image") MultipartFile file, HttpServletRequest request){
//上传的绝对路径 F:/note/assets/
String imgAbPath=abpath+"assets/";
//绝对路径对应urlpath http://localhost:4000/note/assets/
String imgUrlDir="http:"+request.getHeader("Origin").split(":")[1]+":"+port+mdImageDir;
//返回对应的File类型f
File f = FileUtil.upload(file, imgAbPath);
//返回图片地址 http://localhost:4000/note/assets/image-20200924014614792.png 注意图片名子中间有加密
return imgUrlDir+f.getName();
}
}
2.4、使用FileUitl工具函数
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FileUtil {
private static final Logger log = LoggerFactory.getLogger(FileUtil.class);
/**
* 将字符串写入指定文件(当指定的父路径中文件夹不存在时,会最大限度去创建,以保证保存成功!)
*
* @param res 原字符串
* @param filePath 文件路径
* @return 成功标记
*/
public static boolean string2File(String res, String filePath) {
boolean flag = true;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
File distFile = new File(filePath);
if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();
bufferedReader = new BufferedReader(new StringReader(res));
bufferedWriter = new BufferedWriter(new FileWriter(distFile));
char buf[] = new char[1024]; //字符缓冲区
int len;
while ((len = bufferedReader.read(buf)) != -1) {
bufferedWriter.write(buf, 0, len);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
flag = false;
return flag;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
/**
* 获取文件扩展名,不带 .
*/
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* Java文件操作 获取不带扩展名的文件名
*/
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
/**
* 将文件名解析成文件的上传路径
*/
public static File upload(MultipartFile file, String filePath) {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
String name = getFileNameNoEx(file.getOriginalFilename());
String suffix = getExtensionName(file.getOriginalFilename());
String nowStr = "-" + format.format(date);
try {
String fileName = name + nowStr + "." + suffix;
String path = filePath + fileName;
// getCanonicalFile 可解析正确各种路径
File dest = new File(path).getCanonicalFile();
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
if (!dest.getParentFile().mkdirs()) {
System.out.println("was not successful.");
}
}
// 文件写入
file.transferTo(dest);
return dest;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return null;
}
}
这样就实现了在springboot+vue项目中使用mavon-editor了,我们所上传的md文件就保存在了 F:/note/ 中,而图片则保存在了 F:/note/assets 中。