封装微信小程序 图片上传 以及 点击图片放大 预览图片的方法

422 阅读2分钟

最近又又又开始开发微信小程序惹(崩溃.jpg) 因为之前没有意识到这个小程序会做这么久以及会加这么多的新功能,所以导致很多方法没有进行统一的封装处理(果真,工作还是不能过分偷懒的👀)

最近新加的功能里又又又出现了我最头疼的图片上传···,之前每次写都是复制过来的。。。 本着认真负责的态度,决定还是封装下好了😏

首先说明下

我们的图片上传流程是

将选定图片转base64上传到服务器 ==》 返回文件路径

提交表单的时候传upLoad返回的文件路径

首先是until.js 里的代码

// getImage 获取上传图片的临时路径的 Function
// getFileServerPath 获取服务器图片地址的 Function
// fileType 服务器文件位置
const uploadImage = (getImage,getFileServerPath,fileType) => {
  const fileSystemManager = wx.getFileSystemManager()
    wx.chooseImage({   // 这里调起微信选择图片的方法
    count:1,           // 选择图片的数量
    sizeType:['compressed'],
    success:(res)=>{   // 成功的回掉
      const tempFilePaths = res.tempFilePaths
      const size = res.tempFiles[0].size  // 获取上传图片的大小
      if(size >= 10485760){               // 我这里是做了10M的限制
        wx.showModal({
          title: '提示',
          content: '请上传10M以下的图片',
          showCancel:false
        })
        return false
      }
      wx.compressImage({                // 压缩图片
        src: res.tempFilePaths[0],      // 图片路径
        quality: 100,                   // 压缩质量 100等于没压缩 😂
        success:(res1)=>{
          // 转base64
          fileSystemManager.readFile({
            filePath: res1.tempFilePath, // 例如图片临时路径
            encoding: 'base64',
            success (res2) {
              let { data } = res2  // 编码后的数据
              // 调取上传图片的接口
              wx.request({
                url: app.globalData.baseUrl + "/xxxx/uploadFile",
                method: 'post',
                header: {
                  'Authorization': wx.getStorageSync('token'),
                  'content-type': 'application/x-www-form-urlencoded',
                },
                data: {
                  fileType,
                  base:data
                },
                success: function (res) {
                  const {data: {success,result}} = res
                  if (success) {
                    getFileServerPath(result)   // 服务器上图片路径
                  }
                }
              })
            }
          })
        }
      })
      getImage(tempFilePaths[0]) // 上传图片的临时路径
    }
  })
}
// 图片放大
// 需设置data-src 
 const preview =(event) => {
  let currentUrl = event.currentTarget.dataset.src
  wx.previewImage({
    current: currentUrl, // 当前显示图片的http链接
    urls: [currentUrl]// 需要预览的图片http链接列表
  })
}
module.exports = {
  uploadImage:uploadImage,
  preview:preview
}

然后是使用

// 首先是引入
import {uploadImage,preview} from '@/utils/util'
Page({
    data:{
        imageList:[],
        serverPath:[],
    }
    // 上传图片
    upload(){
        const _this = this
        const getImage = function(base64){
          let imageList = [..._this.data.imageList,base64]
          _this.setData({imageList})
        }
        const getServerPath = function(path){
          if(_this.data.imageVerification){
            _this.setData({imageVerification:false})
          }
          let serverPath = [..._this.data.serverPath,path]
          _this.setData({serverPath})
        }
        uploadImage(
          getImage,
          getServerPath,
          'events'
        )
    },
    // 发大预览
    preview(e){
        preview(e)
    },
})

大致效果就是这样

image.png

上传

image.png

预览

image.png

哇咔咔。搞定,以后再也不用复制那么长的代码了😭