微信小程序-图片上传功能的实现
微信小程序-图片上传功能的实现
以下代码完整,能够正常实现微信小程序的图片上传功能,大家可以借鉴一下。
1.index.wxml
<view class="uploader-text" bindtap="doUpload"><text>上传图片</text></view>
2.index.js
Page({
// 上传图片doUpload: function () {// 选择图片wx.chooseImage({count: 1,sizeType: ['compressed'],sourceType: ['album', 'camera'],success: function (res) {wx.showLoading({title: '上传中',})const filePath = res.tempFilePaths[0]// 上传图片const cloudPath = `my-image${filePath.match(/\.[^.]+?$/)[0]}`wx.cloud.uploadFile({cloudPath,filePath,success: res => {console.log('[上传文件] 成功:', res)app.globalData.fileID = res.fileIDapp.globalData.cloudPath = cloudPathapp.globalData.imagePath = filePathwx.navigateTo({url: '../storageConsole/storageConsole'})},fail: e => {console.error('[上传文件] 失败:', e)wx.showToast({icon: 'none',title: '上传失败',})},complete: () => {wx.hideLoading()}})},fail: e => {console.error(e)}})}
})
3.也可参考下微信官方文档
https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html