簡介
v-md-editor 是基于 Vue 開發的 markdown 編輯器組件,即支持vue2也支持vue3。
- gitee:https://gitee.com/ckang1229/vue-markdown-editor
- 文檔:https://code-farmer-i.github.io/vue-markdown-editor/zh/
服務器端代碼
@RestController
@RequestMapping("/file")
public class FileUploadController {/*** 上傳文件,指定上傳到的目錄并重命名** @param file* @param path 文件在服務器的路徑【不帶問號后面的坐標】,如果路徑不存在,會自動創建* @return*/@SaCheckLogin@PostMapping("/upload")@LogAnno(value = "上傳文件", opt = OptEnum.INSERT)public ResultBean<String> upload(MultipartFile file, String path) {// ……return ResultBeanUtil.success(url).setMsg("文件上傳成功!");}
}
上傳成功返回數據示意:
[{"code": 200,"msg": "文件上傳成功!","data": "http://127.0.0.1:9005/tiku-resources/ae83c411083848a69efccf7094183348.png"}
]
vue頁面
<template><div><!-- 編輯 --><v-md-editormode="edit"v-model="content"height="400px":disabled-menus="[]"@upload-image="handleUploadImage"></v-md-editor><!-- 預覽 --><v-md-editor v-model="content" mode="preview" /></div>
</template><script setup lang="ts" name="markdown">
import { ref } from "vue";
import { ElMessageBox } from "element-plus";
import { println } from "@/utils/util";
import { uploadPic } from "../course/api/course";
import { ResultEnum } from "@/utils/constant";
const content = ref(`請輸入內容`);// 請求頭:圖片上傳時需要登錄權限
const handleUploadImage = (event, insertImage, files) => {// 拿到 files 之后上傳到文件服務器,然后向編輯框中插入對應的內容const formData = new FormData();formData.append("file", files[0]);uploadPic({ file: formData }).then(res => {println("文件上傳:", res);if (res && res.code === ResultEnum.SUCCESS && res.data) {insertImage({ url: res.data });}});
};
</script>
上面代碼使用FormData通過axios把文件上傳到服務器,然后通過url進行圖片的回顯。FormData介紹:FormData 接口提供了一種表示表單數據的鍵值對 key/value 的構造方式,創建的FormData對象會自動將form中的表單值也包含進去,包括文件內容也會被編碼之后包含進去。然后后端就可以通過MartpartFile進行接收該圖片文件然后進行文件的 存儲 。
v-md-editor 常用API屬性:
- text:需要解析預覽的 markdown 字符串。
- v-model:支持雙向綁定。
- mode:模式。可選值:edit(純編輯模式) editable(編輯與預覽模式) preview(純預覽模式)。
- default-fullscreen:是否默認開啟全屏。
- disabled-menus:禁用的菜單。默認值為 image 工具欄下的上傳本地圖片菜單