一、前台处理
(1)首先在wxml中为按钮绑定上传图片事件
<button bindtap="upImgClick">上传图片</button> <image src='{{imgUrl}}'></image> //显示图片
(2)在页面对应的.js文件的data中添加存储图片数据库地址的变量(imgUrl)以便展示,添加上传图片的方法:利用微信的wx.chooseImage接口获取图片的临时地址filepath,将临时地址传入后台,并接收后台传递的服务器地址,赋给imgUrl
.js文件.
upImg.js var util = require('../../utils/util.js') Page({ data: { imgUrl:'', }, //上传图片 upImgClick: function (e){ wx.chooseImage({ count: 1, //一次上传图片数量 sizeType: ['compressed'], //图片大小 sourceType: ['album', 'camera'], success: function (res) { util.showBusy('正在上传') var filePath = res.tempFilePaths[0] //获取图片路径 // 上传图片 wx.uploadFile({ url: config.service.uploadUrl, //服务器接口地址 filePath: filePath, name: 'file', success: function (res) { util.showSuccess('上传图片成功') console.log(res) res = JSON.parse(res.data) console.log(res) that.setData({ imgUrl: res.data.imgUrl }) }, fail: function (e) { util.showModel('上传图片失败') } }) }, fail: function (e) { console.error(e) } }) }, )}
(3)util.js文件
util.js // 显示繁忙提示 var showBusy = text => wx.showToast({ title: text, icon: 'loading', duration: 10000 }) // 显示成功提示 var showSuccess = text => wx.showToast({ title: text, icon: 'success' }) // 显示失败提示 var showModel = (title, content) => { wx.hideToast(); wx.showModal({ title, content: JSON.stringify(content), showCancel: false }) } module.exports = { showBusy, showSuccess, showModel }
二、node.js后台处理
(1)后台获取图片临时地后,用uploader获取图片服务器地址,然后将服务器地址返回前台
uploadUrl.js const fs = require('fs') module.exports = async ctx => { // 获取上传之后的结果 // 具体可以查看: const data = await uploader(ctx.req) ctx.state.data = data ctx.body = { data: data } }