
本文章向大家介紹WangEditor 提交base64格式圖片上傳至服務(wù)器,主要包括WangEditor 提交base64格式圖片上傳至服務(wù)器使用實例、應(yīng)用技巧、基本知識點總結(jié)和需要注意事項,具有一定的參考價值,需要的朋友可以參考一下。
2.引入安裝
友情提示:多商戶,PRO,多店版,陀螺匠的項目找到wangEditor的組件參考修改可直接使用。
// 安裝
npm i wangeditor --save
// 使用
import E from "wangeditor"
this.editor = new E(this.$refs['wang-editor']);
3.使用
定義上傳圖片,先轉(zhuǎn)base64,轉(zhuǎn)blob,上傳服務(wù)器
mounted() {
this.createEditor();
},
methods: {
createEditor() {
let _this = this;
const menuKey = 'alertMenuKey';
const html = 'alertHtml';
this.editor = new E(this.$refs['wang-editor']);
this.editor.menus.extend(menuKey, AlertMenu);
this.editor.menus.extend(html, HtmlMenu);
this.editor.config.menus = this.editor.config.menus.concat(html);
this.editor.config.menus = this.editor.config.menus.concat(menuKey);
this.editor.config.uploadImgFromMedia = function () {
_this.getimg();
};
// this.editor.config.uploadVideoHeaders = _this.header;
this.editor.config.height = 600;
this.editor.config.menus = [
'alertHtml',
'head',
'bold',
'fontSize',
'fontName',
'italic',
'underline',
'strikeThrough',
'indent',
'lineHeight',
'foreColor',
'backColor',
'link',
'list',
// "todo",
'justify',
'quote',
'image',
'alertMenuKey',
// "table",
'code',
'splitLine',
];
this.editor.config.customUploadImg = function (files, insert) {
// 上傳代碼返回結(jié)果之后,將圖片插入到編輯器中
_this.filesToBase64(files);
};
// 配置全屏功能按鈕是否展示
// this.editor.config.showFullScreen = false
this.editor.config.uploadImgShowBase64 = true;
// this.editor.config.uploadImgAccept = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
this.editor.config.zIndex = 0;
// this.editor.config.uploadImgMaxSize = this.uploadSize * 1024 * 1024
this.editor.config.compatibleMode = () => {
// 返回 true 表示使用兼容模式;返回 false 使用標(biāo)準(zhǔn)模式
return true;
};
this.editor.config.onchange = (newHtml) => {
this.newHtml = newHtml;
this.$emit('editorContent', newHtml);
};
this.editor.config.onchangeTimeout = 300; // change后多久更新數(shù)據(jù)
this.editor.create();
},
filesToBase64(files) {
let _this = this;
files.map((item) => {
var reader = new FileReader();
reader.onload = function (event) {
var base64_str = event.target.result;
//div中的img標(biāo)簽src屬性賦值,可以直接展示圖片
var bytes = window.atob(base64_str.split(',')[1]);
var array = [];
for (let i = 0; i < bytes.length; i++) {
array.push(bytes.charCodeAt(i));
}
var blob = new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
var formData = new FormData();
formData.append('file', blob, Date.now() + '.jpg');
formData.append('filename', 'file');
fetch('http://xxx.xxx.xxx/upload/image/0/file', {
method: 'post',
headers: {
'X-Token':localStorage.getItem('token'),//token的key和value值根據(jù)自己項目進(jìn)行修改
},
body: formData,
})
.then((response) => response.json())
.then((res) => {
console.log(res.data);
_this.editor.cmd.do('insertHTML', ``);
//模板字符串拼接的圖片路徑層級也根據(jù)自己項目返回內(nèi)容進(jìn)行調(diào)整
});
};
// 傳入一個參數(shù)對象即可得到基于該參數(shù)對象的文本內(nèi)容
reader.readAsDataURL(item);
});
},
},