小程序(二十五)微信小程序富文本编辑器editor上传图片

本文探讨了将微信小程序中图片上传功能从本地缓存切换到服务器的过程,展示了如何使用wx.uploadFile API实现图片上传,并结合editor组件进行操作,包括选择图片、上传验证及成功插入图片的示例。
摘要由CSDN通过智能技术生成

官方给出的示例代码中图片上传功能是将图片上传至小程序的缓存中,代码如下所示:

  insertImage(e) {
    console.log(e);
    const that = this
    wx.chooseImage({
      count: 1,
      success: function (res) {
        console.log(res);
        that.editorCtx.insertImage({
          src: res.tempFilePaths[0],
          data: {
            id: 'abcd',
            role: 'god'
          },
          width: '80%',
          success: function () {
            console.log('insert image success')
          }
        })
      }
    })
  }

我这里封装的editor自定义组件图片上传也是同官方给出的示例一致,也是使用的小程序缓存。

但是在实际开发中,图片我们还是需要上传至服务器中的。

小程序上传文件需要使用到 wx.uploadFile 这个API,这里我不做赘述,直接上代码:

/**、
   * 插入图片
   */
  insertImageEvent() {
    var self = this;
    wx.chooseImage({
      count: 1,
      success: response => {
        let path = response.tempFilePaths[0];
        //调用子组件方法,图片应先上传再插入,不然预览时无法查看图片。(这里调用子组件查看存至本地的临时图片)
        // richText.insertImageMethod(path).then(result => {
        //   console.log('[insert image fail callback]=>', result)
        // }).catch(res => {
        //   console.log('[insert image fail callback]=>', res)
        // });//*/
        wx.uploadFile({ //把临时图片上传到服务器
          url: app._server + '/xxx/xxxxxx,
          filePath: response.tempFilePaths[0],
          file: response.tempFilePaths[0],
          name: 'file',
          formData: {
            project_id:id,
          },
          success: (res) => {
            let updata = JSON.parse(res.data);
            console.log(updata);
            if (updata.code == 1) {
              richText.editorCtx.insertImage({ //这里是富文本编辑器 editor 组件插入图片方法;
                src: updata.data,
                data: {
                  id: 'imgage',
                  role: 'god'
                },
                // width: '80%',
                success: () => {
                  console.log('insert image success')
                }
              })
            }//*/
          },error(result){
            console.log(result)
          }
        });
      }
    })
  },
 

以上的代码便是我在实际开发中使用到的图片上传的代码。

有好的建议,请在下方输入你的评论。

欢迎访问个人博客
https://guanchao.site

欢迎访问小程序:

在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值