有勇气的牛排博客

微信小程序上传图片

有勇气的牛排 1340 微信开发 2021-08-26 21:57:34

1介绍

使用vant组件库

2 index.html

<form bindsubmit='res'> <view style="position:relative;top:0rpx;float:left;"> <van-uploader max-count="1" bind:after-read="afterRead" /> </view> <image src="" style="width:200rpx;height:200rpx;"></image> <van-button form-type='submit' type="primary" size="large" custom-style="width:100%;">提交信息</van-button> </form>

3 index.json

{ "usingComponents": { "van-button": "@vant/weapp/button/index", "van-uploader": "@vant/weapp/uploader/index" } }

4 index.js

var app = getApp(); var imageUrl = null; // 上传图片后获得的链接 Page({ data: { fileList: "", }, // 读取到图片 即上传 afterRead(event) { var that = this; that.setData({ fileList: [] }) const { file } = event.detail; console.log(event.detail) // 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式 wx.uploadFile({ url: app.globalData.url + 'upload', // 仅为示例,非真实的接口地址 filePath: file.url, name: 'file', formData: { user: 'test' }, success(res) { // 上传完成需要更新 fileList // console.log(res.data) var res1 = JSON.parse(res.data) console.log(res1.results) imageUrl = res1.url; that.setData({ fileList: res1.results, url: res1.url // 这里的参数传到 微信小程序前端 可以即时加载出 我们刚才上传的图片 }) }, }); }, onLoad: function (options) { }, onShow: function () { }, // 提交信息 res: function (e) { console.log("提交信息") // var now_price = e.detail.value.now_price // console.log(title) if (imageUrl == null) { wx.showToast({ image: '../../images/toast/error.png', title: "请上传图片", }) return; } wx.showModal({ title: '提示', content: '确认添加', success: function (res) { if (res.confirm) { console.log('用户点击确定') wx.request({ url: app.globalData.url + "uploadReport", method: 'POST', data: { sessionId: wx.getStorageSync("sessionId"), // title: title, imageUrl: imageUrl }, header: { // 'content-type': 'application/json' // GET "Content-Type": "application/x-www-form-urlencoded"// POST }, success(res) { console.log("添加商品结果") console.log(res) if (res.data.status == 1) { wx.showToast({ image: '../../images/toast/success.png', title: "添加成功", }) wx.switchTab({ url: '/pages/index/index' }); } if (res.data.data == 0) { wx.showToast({ image: '../../images/toast/error.png', title: "添加失败", }) } } }) } else if (res.cancel) { console.log('用户点击取消') } } }) }, })

5 效果

https://static.couragesteak.com/article/72601ef37b633aded10f8fe4c66df342.png


留言

专栏
文章
加入群聊