以前没有小程序富文本编辑器, 只能输入文字, 图片上传后, 在服务端进行拼接. 现在好啦, 直接上富文本, 向里面传图片, 修改图片大小.
主要是富文本里插入图片, 选择图片, 一个临时地址, 预览地址, 上传服务器后返回的图片地址.
在微信小程序基础库 2.7 以前 (目前最新为 2.7.1) 是没有富文本编辑器的, 只能通过 textarea 和图片选择器, 将文本和图片在服务端进行组装. 目前网络上也几乎没有一个完整的例子出来(因为今年 5 月份刚推出来).
有了富文本编辑器, 就可以愉快地发布图文了. 瞧它功能还是挺丰富, 加粗, 斜体, 下划线, 左中右对齐...... 背景色, 标题, 插入当前日期, 事项, 列表,
当然, 最主要还是图片上传 (理论上是不是没有 6 幅图 9 幅图的数量限制啦?), 点击图片, 还可以删除, 整个编辑区的删除请使用哪个回收站(垃圾桶) 的图标...... 当然, 它传到服务端的带标签的 html, 解析还是依靠 wxparse 珠三角设代小程序 plus 版已经整合完毕.
相比之前的文本 + 图片组装模式, 这里可以给每个图片进行说明了. 甚至给每个图片下方添加图片名称. 当然, 手机上操作这些稍嫌麻烦, 用语音输入文字, 速度就快很多了.
JS:
- insertImage() {
- const that = this
- wx.chooseImage({
- count: 6,
- sizeType: ['original', 'compressed'],
- sourceType: ['album', 'camera'],
- success: res => {
- const images = that.data.images.concat(res.tempFilePaths)
- console.log(res.tempFilePaths)
- that.data.images = images.length <= 6 ? images : images.slice(0, 6)
- $digest(that)
- const arr = []
- // console.log(that.data.images)
- for (let path of that.data.images) {
- arr.push(wxUploadFile({
- // url: config.urls.question + '/image/upload',
- url: config.url + '/wx/uploadwxeditorimg',
- filePath: path,
- name: 'file',
- }))
- }
- // console.log(arr)
- Promise.all(arr).then(res => {
- return res.map(item => JSON.parse(item.data).link)
- }).catch(err => {
- console.log(">>>> upload images error:", err)
- }).then(urls => {
- // console.log(urls)
- for (let i = 0; i <urls.length; ++i) {
- that.editorCtx.insertImage({
- src: config.attachmenturl + urls[i],
- // data: {
- // id: 'abcd',
- // role: 'god'
- // },
- success: function () {
- console.log('insert image success')
- that.setData({
- images: []// 这里清 0, 否则总是将上次的图片带上
- })
- // console.log(that.data.images)
- }
- })
- }
- })
- }
- })
- },
- handleContentInput(e) {
const value = e.detail.HTML
- // 要将图片的头 http://*.*.*. 去掉 / at/g
- var reg = new RegExp(config.attachmenturl, "g")
- this.data.content = value.replace(reg, '');
- },
- submitForm(e) {
- var that = this
- const title = this.data.title
- const content = this.data.content
- if (title && content) {
- // 登录
- var sessionId = wx.getStorageSync('sessionId')
- // 发起网络请求
- wx.request({
- url: config.url + '/wx/addwxeditorarticle',
- header: {
- "Content-Type": "application/x-www-form-urlencoded"
- },
- method: "POST",
- data: {
- hotqinsessionid: sessionId,
- title: title,
- content: content
- },
- success: function (res) {
- if (res.data.status == 0) {
- wx.showToast({
- title: res.data.info,
- icon: 'loading',
- duration: 1500
- })
- } else {
- wx.showToast({
- title: res.data.info, // 这里打印出成功
- icon: 'success',
- duration: 1000
- })
- // 进行清理
- that.editorCtx.clear({
- success: (res) => {
- console.log('succ:' + res)
- },
- fail: (res) => {
- console.log('fail:' + res)
- }
- })
- wx.navigateTo({
- url: `../detail/detail?id=` + res.data.id
- })
- }
- }
- })
- } else {
- wx.showToast({
- title: "标题或正文不能为空!",
- icon: 'loading',
- duration: 1500
- })
- }
- },
来源: https://www.qcloud.com/developer/article/1446328