wangEditor 上传附件

创建 wangEditor

创建一个index.js文件

import React, { Component } from 'react'
import Wangeditor from 'wangeditor'
export default class RcWangEdite extends Component {constructor(props) {super(props)this.containerRef = React.createRef()}componentDidMount = () => {const div = this.containerRef.current;const editor = new Wangeditor(div);this.editor = editor;this.setCustomConfig();editor.create();};onChange = html => {this.props.onChange(html);};setCustomConfig = () => {const { customConfig } = this.props;this.editor.customConfig = {// 关闭粘贴内容中的样式pasteFilterStyle: false,// 忽略粘贴内容中的图片pasteIgnoreImg: true,// 使用 base64 保存图片uploadImgShowBase64: true...customConfig,};};render() {return <div  ref={this.containerRef} />>;}
}

添加上传图片

修改setCustomConfig这个方法

setCustomConfig = () => {const { customConfig } = this.propsthis.editor.customConfig = {// 关闭粘贴内容中的样式pasteFilterStyle: false,// 忽略粘贴内容中的图片pasteIgnoreImg: true,// 上传图片到服务器uploadFileName: 'image', //设置文件上传的参数名称uploadImgServer: commonApi.imgUploadApi, //设置上传文件的服务器路径uploadImgMaxSize: 10 * 1024 * 1024, // 将图片大小限制为 10MuploadImgHooks: {before: function(xhr, editor, files) {before && before(xhr, editor, files)},fail: function(xhr, editor, result) {fail && fail(xhr, editor, result)},error: function(xhr, editor) {error && error(xhr, editor)},timeout: function(xhr, editor) {timeout && timeout(xhr, editor)},customInsert: (insertImg, result) => {const { code, data, msg } = resultif (code == 0) {insertImg('/CMMS' + data.image_url)} else {message.error(msg)}},},...customConfig,}
}

上传附件

首先我们写一个fileMenu.js的文件

/**editor: wangEdit的实例editorSelector: wangEdit挂载点的节点options: 一些配置
*/
export default (editor, editorSelector, options) => {editor.fileMenu = {init: function(editor, editorSelector) {const div = document.createElement('div')div.className = 'w-e-menu'div.style.zIndex = 10001const rdn = new Date().getTime()div.onclick = function() {document.getElementById(`up-${rdn}`).click()}const input = document.createElement('input')input.type = 'file'input.name = 'file'input.id = `up-${rdn}`input.className = 'upload-file-input'div.innerHTML = `<span class="upload-file-span">上传附件</span>`div.appendChild(input)editorSelector.getElementsByClassName('w-e-toolbar')[0].append(div)},}// 创建完之后立即实例化editor.fileMenu.init(editor, editorSelector)
}

index.js中引入fileMenu.js

import fileMenu from './fileMenu';
...
...
// 修改componentDidMount
componentDidMount = () => {const div = this.containerRef.current;const editor = new Wangeditor(div);this.editor = editor;this.setCustomConfig();editor.create();// 要放在editor实例化之后创建上传菜单fileMenu(editor, this.containerRef.current);};

做完这一步之后,wangEditor 富文本的菜单栏上已经有上传附件的按钮,并且点击可以选择文件了

对选择的文件进行上传

写一个上传文件的 js,uploadFile.js

import { message } from 'antd'
function uploadFile(files, options) {if (!files || !files.length) {return}let uploadFileServer = commonApi.imgUploadApi //上传地址const maxSize = 100 * 1024 * 1024 //100Mconst maxSizeM = maxSize / 1000 / 1000const maxLength = 1const uploadFileName = 'file'const uploadFileParams = {}const uploadFileParamsWithUrl = {}const timeout = 5 * 60 * 1000 //5 min// ------------------------------ 验证文件信息 ------------------------------const resultFiles = []const errInfo = []for (let file of files) {const name = file.nameconst size = file.size// chrome 低版本 name === undefinedif (!name || !size) {return}if (maxSize < size) {// 上传附件过大errInfo.push('\u3010' + name + '\u3011\u5927\u4E8E ' + maxSizeM + 'M')return}// 验证通过的加入结果列表resultFiles.push(file)}// 抛出验证信息if (errInfo.length) {this._alert('附件验证未通过: \n' + errInfo.join('\n'))return}if (resultFiles.length > maxLength) {this._alert('一次最多上传' + maxLength + '个文件')return}// ------------------------------ 自定义上传 ------------------------------// 添加附件数据const formdata = new FormData()for (let file of resultFiles) {const name = uploadFileName || file.nameformdata.append(name, file)}// ------------------------------ 上传附件 ------------------------------if (uploadFileServer && typeof uploadFileServer === 'string') {for (key in uploadFileParams) {val = encodeURIComponent(uploadFileParams[val])formdata.append(key, val)}// 定义 xhrconst xhr = new XMLHttpRequest()xhr.open('POST', uploadFileServer)// 设置超时xhr.timeout = timeoutxhr.ontimeout = function() {if (options.timeout && typeof options.timeout === 'function') {options.timeout(xhr, editor)}message.error('上传附件超时')}// 监控 progressif (xhr.upload) {xhr.upload.onprogress = function(e) {let percent = void 0// 进度条if (e.lengthComputable) {percent = e.loaded / e.totalif (options.onProgress && typeof options.onProgress === 'function') {options.onProgress(percent)}}}}// 返回数据xhr.onreadystatechange = function() {let result = void 0if (xhr.readyState === 4) {if (xhr.status < 200 || xhr.status >= 300) {// hook - errorif (options.onFail && typeof options.onFail === 'function') {options.onFail(xhr, editor)}return}result = xhr.responseTextif ((typeof result === 'undefined' ? 'undefined' : typeof result) !== 'object') {try {result = JSON.parse(result)} catch (ex) {// hook - failif (options.onFail && typeof options.onFail === 'function') {options.onFail(xhr, editor, result)}return}}const data = result || []if (data.code == 0) {options.onOk && options.onOk(data.data)}}}// 自定义 headersfor (let key in uploadFileHeaders) {xhr.setRequestHeader(key, uploadFileHeaders[key])}// 跨域传 cookiexhr.withCredentials = false// 发送请求xhr.send(formdata)}
}
export default uploadFile

粗略的封装了一个上传文件的方法,options 主要暴露有以下几个 api

name des
timeout 超时的回调
onProgress 上传进度的回调
onFail 上传失败的回调
onOk 上传成功的回调

其他的需要扩展的,可以自行添加

fileMenu.js中引入uploadFile.js

import uploadFile from './uploadFile';
...
...
// 修改`init`方法, 给`input`加上`onChange`事件
editor.fileMenu = {init: function(editor, editorSelector) {......input.onchange = e => {// 使用uploadFile上传文件uploadFile(e.target.files, {onOk: data => {console.log(data)// 可以使用editor.txt.html(data)进行更新},onFail: err => {console.log(err)},onProgress: percent => {console.log(percent)},});};},......
};

就这样子,wangEditor 实现了上传富文本的功能,wangEditor 也封装好了

wangEditor 上传附件相关推荐

  1. wangeditor: 上传图片+上传视频+上传附件(自定义)完整使用

    wangeditor: 上传图片+上传视频+上传附件(自定义)完整使用 一:项目需求:①角色为管理员可以新增编辑文章 + ②点击可以看文章详情 +③ 角色为管理员可以修改编辑文章 二:效果: ①角色为 ...

  2. SAP 没有QM02权限的情况下如何为一个质量通知单单据上传附件?

    SAP 没有QM02权限的情况下如何为一个质量通知单单据上传附件? 正常情况,我们可以在QM01/QM02事务代码创建或者修改一个Quality Notification(质量通知单)的时候上传附件. ...

  3. SAP MM 给合同的ITEM上传附件以及附件查询

    SAP MM 给合同的ITEM上传附件以及附件查询 1,使用事务代码 CV01N为合同上传附件, Document:输入6100000829, Document type 101 (contract) ...

  4. 修改上传附件大小限制方法

    2019独角兽企业重金招聘Python工程师标准>>> 上传附件是大家经常需要操作的,但是很多情况都会限制上传附件的大小.那么如何修改上传附件大小限制呢? 修改上传附件大小限制方法 ...

  5. SharePoint 2010 列表项代码绑定附件心得 (FileUpload上传附件)

    最近项目中用到在插入Item时绑定附件,可以上传多个附件,很快就写出来了,可是测试一侧老是有问题,经过多番折腾,终于算通过测试.SharePoint 2010上传附件需注意一下几点: 判断文件是否为空 ...

  6. iis mysql php 附件上传大小_修改上传附件2M大小限制的方法/php+iis上传附件默认大小修改方法...

    在服务器上架设好WordPress后,使用过程中发现,上传附件大小有2M的限制 话说服务器就是本机,可以直接把文件拖到附件存储文件夹下,然后在需要附件的地方引用链接 可是这种落后的方法终究不是办法,还 ...

  7. j2ee之页面无刷新上传附件

    //上传附件 var uploadAnnex = function(){//alert("??");//document.getElementById('submitFile'). ...

  8. salesforce零基础学习(八十九)使用 input type=file 以及RemoteAction方式上传附件

    在classic环境中,salesforce提供了<apex:inputFile>标签用来实现附件的上传以及内容获取.salesforce 零基础学习(二十四)解析csv格式内容中有类似的 ...

  9. 上传附件删除、session清空问题

    最近因为项目的需要,将客户端附件上传至服务器,附件上传的位置是IIS目录下的文件夹,经过处理之后.必须将该附件删除. 程序发布之后,使用该功能,结果项目无法运行.必须要重新启动IIS才可以重新运行整个 ...

  10. 20100519 学习记录:asp CreateFolder/上传附件

    新增一个上传附件的功能. 在网上找了一下,基本都是在化境HTTP上传程序基础上改的,灰常感谢这个源代码的开发者,深深鞠躬. 不过这个代码要求在上传图片时,输入的文件夹必须是已存在的文件夹,不然就会出错 ...

最新文章

  1. android studio 开发环境搭建
  2. LeetCode-1.Two Sum
  3. Ubuntu12.10 root用户登录设置
  4. ASP.NET MVC (五、HttpClient接口解析)
  5. oracle 11g禁用和强制direct path read
  6. linux软件包管理工具,Linux 软件包管理器-----yum配置详解一
  7. MySQL基础篇(01):经典实用查询案例,总结整理
  8. PDM 物理模型codename转大写
  9. PostgreSQL中定时job执行(pgAgent)
  10. 浏览器兼容性小记-DOM篇(二)
  11. 电商常用字体_字体商用有风险,侵权罚款上千万!告诉你怎么正确使用
  12. win11如何取消开机自检 windows11取消开机自检的设置方法
  13. liunx下安装tomcat7.0.82
  14. 模拟某个浏览器抓取数据
  15. web技术分享| WebRTC控制摄像机平移、倾斜和缩放
  16. 文件及文件夹删除失败的解决方法
  17. lzy的游戏【思维分析】【背包】
  18. 中药知多少!!!!!
  19. nova7可以升级成鸿蒙20系统,华为nova7升级到EMUI11,8大功能提升,带来更新体验...
  20. Android 深入理解 ANR 触发原理:Service

热门文章

  1. php的include once,php include_once的使用方法详解
  2. 虚拟机安装黑苹果mac 10.12系统安装教程
  3. 微信群控云控客服开发SDK
  4. 开启了国内弹幕文化的先河,实现B站弹幕很难么?这个开源项目了解一下
  5. 通过AT指令将air202 接入阿里云
  6. 2022-2028年中国产学研合作行业深度调查与战略咨询报告
  7. iPhone屏幕数据
  8. Axure8.0使用教程
  9. .net core 系列
  10. 淘宝上线独立搜索引擎一淘网