微信小程序上传图片的代码怎么写?
发布时间:2024-06-06 00:00:00
阅读:153
字数:1663


微信小程序上传图片的代码

应用到API:

wx.chooseImage
wx.showLoading
wx.uploadFile
wx.showToast
wx.showLoading
wx.hideLoading


<  button type="primary" bindtap="doUpload" style="margin-top: 150rpx;">上传图片
doUpload: function () { // 选择图片 let that = this; wx.chooseImage({ count: 5 - that.data.img_arr.length, //上传图片的数量 当之前上传了部分图片时 ,总数 - 已上传数 = 剩余数 (限制上传的数量) sizeType: ['compressed'], sourceType: ['album', 'camera'],//指定图片来源是相机还是相册,默认二者都有 success: function (res) { const tempFiles = res.tempFiles //包含图片大小的数组 console.log(tempFiles,"查看tempFiles的信息"); wx.showLoading({ title: '上传中', }) console.log(res); // const filePath = res.tempFilePaths[0] wx.uploadFile({ url: 'https://*******/Index/Api/insert', //仅为示例,非真实的接口地址 filePath: res.tempFilePaths[0], name: 'img', formData: { }, success (res){ const data = res.data console.log(data); //返回图片名称 if (res.data!='') { wx.hideLoading({ success: (res) => { setTimeout(() => { wx.showToast({ title: '上传成功!', }) }, 2000); }, }) } else { wx.hideLoading({ success: (res) => { setTimeout(() => { wx.showToast({ title: '上传失败!', icon:'none' }) }, 2000); }, }) } //do something } }) }, fail: e => { console.error(e) } }) },