wangEditor添加上传文件功能
<script>
const { createEditor, createToolbar, Boot, SlateTransforms } = window.wangEditor;
const editorConfig = {
MENU_CONF: {},
placeholder: '文章内容',
onChange(editor) {
const html = editor.getHtml()
},
};
class MyModalMenu {
constructor(){
this.title = '文件上传'
this.tag = 'button'
this.showModal = true
this.modalWidth = 300
}
isActive(editor){
return false
}
getValue(editor){
return ''
}
isDisabled(editor){
return false
}
exec(editor, value){
}
getModalPositionNode(editor){
return null
}
getModalContentElem(editor){
const $content = $('<div></div>');
const $nameInput = $('<input type="text" placeholder="请输入附件名称">');
$content.append($('<label>附件名称:</label>'));
$content.append($nameInput);
$content.append($('<br><br>'));
const $fileInput = $('<input type="file">');
$content.append($('<label>选择附件:</label>'));
$content.append($fileInput);
$content.append($('<br><br>'));
const $uploadButton = $('<button>上传附件</button>');
$content.append($uploadButton);
$content.append($('<br><br>'));
$uploadButton.on('click', () => {
const file = $fileInput[0].files[0];
const fileName = $nameInput.val();
if (!file) {
alert('请选择一个文件');
return;
}
const formData = new FormData();
formData.append('file', file);
$.ajax({
url: "{:url('uploadFiles')}",
type: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
success: function (data) {
if (data.errno === 0) {
const attachmentUrl = data.data.url;
const node = {
type: 'link',
url: attachmentUrl,
target: '_blank',
children: [{ text: fileName || '附件' }]
}
editor.focus();
editor.insertNode(node);
} else {
alert('上传失败:' + data.message);
}
},
error: function (xhr, status, error) {
console.error('上传出错:', error);
alert('上传出错,请稍后再试');
}
});
});
// 返回自定义的模态框内容
return $content[0];
}
}
const menuiConf = {
key: 'menu1',
factory(){
return new MyModalMenu()
}
};
const module = {
menus: [menuiConf],
};
Boot.registerModule(module);
const editor = createEditor({
selector: '#editor-container',
html: '{$res.articlecontent|raw}',
config: editorConfig,
mode: 'default',
});
const toolbarConfig = {};
toolbarConfig.insertKeys = {
index: -1,
keys: ['menu1'],
};
const toolbar = createToolbar({
editor,
selector: '#toolbar-container',
config: toolbarConfig,
mode: 'default',
});
</script>