小程序 - 上传图片到云开发后台

本文介绍如何在小程序中实现图片上传功能,结合云开发后台,详细讲解pages/index/index.wxml和index.js的实现过程,助你掌握小程序与云服务的结合应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pages/index/index.wxml

<!--index.wxml-->
<view>云函数调用的例子</view>

<button type="default" style="width: 600rpx; margin: 50rpx;" bindtap="handleOk">调用yunfoo云函数</button>
<button type="default" style="width: 600rpx; margin: 50rpx;" bindtap="handleUploadFile">上传图片到云开发</button>
<image src="{{imageSrc}}"></image>
<button type="default" style="width: 600rpx; margin: 50rpx;" bindtap="handleDownLoad">上传图片到云开发</button>
<image src="{{downloadImg}}"></image>

pages/index/index.js

//index.js
Page({
  data:{
    imageSrc: '',
    downloadImg:''
  },
  // 下载图片
  handleDownLoad(){
    wx.cloud.downloadFile({
      fileID:'cloud://prod-8g32phui17ada975.7072-prod-8g32phui17ada975-1307410307/1631430940810cloud.jpg',
      success:(res)=>{
        console.log(res)
        this.setData({
          downloadImg: res.tempFilePath
        })
      }
    })
  },
  // 上传图片到云开发
  handleUploadFile(){
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res)=> {
      // tempFilePath可以作为img标签的src属性显示图片
      // console.log(res)
      // 上传路径
      const filePath = res.tempFilePaths[0]
      // 上传图片的名字
      const cloudPath = 'cloud' + Date.now() +  filePath.match(/\.[^.]+?$/)[0]
      console.log(filePath,cloudPath)
      // 上传到云开发
      wx.cloud.uploadFile({
        filePath:filePath,
        cloudPath:cloudPath,
        success: (res)=>{
          console.log(res) // fileID
          this.setData({
            imageSrc: res.fileID
          })
        }
      })
      }
    })
  },
  // 调用yunfoo云函数
  handleOk(){
    // 调用 新建云函数 wx.cloud.callFunction()
    wx.cloud.callFunction({
      name: 'yunfoo',
      data:{
        a: 1,
        b: 2
      },
      success: (res)=>{
        console.log(res)
      },
      fail: (err)=>{
        console.log(err)
      },
      complete:()=>{
        console.log('yunfoo 函数调用完毕')
      },
    })
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值