微信小程序的上传图片或者其他文件的简单小例子

本文介绍了一种使用微信小程序进行文件上传的方法,详细展示了如何通过chooseMessageFile和cloud.uploadFile API选择并上传各种类型的文件到云存储,包括处理文件路径和扩展名的技巧。
<button bindtap="uploadEvent" type="primary">上传</button>
<image src="{{imgSrc}}" style="width:100%" mode="widthFix"></image>
uploadEvent(){
    // //1.选择图片,本机相册
    // wx.chooseImage({
    //   success:(res)=>{
    //     console.log(res)
    //     //res.tempFilePaths[0]
    //     //2.上传图片
    //     wx.cloud.uploadFile({
    //       cloudPath:new Date().valueOf()+'.png',
    //       filePath:res.tempFilePaths[0],
    //       success:(result)=>{
    //         console.log(result)
    //         this.setData({
    //           imgSrc:result.fileID,
    //         })
    //       }
    //     })
    //   }
    //   ,fail:(err)=>{
    //     console.log(err)
    //   }
    // })
        //4.想试一下别的文件
        wx.chooseMessageFile({
          success:(res)=>{
            console.log(res)
            //res.tempFiles[0].path
            if(res.tempFiles.length>0){
              wx.cloud.uploadFile({
                //这个地方需要加上后缀
                cloudPath:new Date().valueOf()+'.'+res.tempFiles[0].name.split('.').pop(),
                filePath:res.tempFiles[0].path,
                success:(result)=>{
                  console.log(result)
                  wx.showToast({
                    title: 'success',
                    duration:1000,
                  })
                  this.setData({
                    //imgSrc:result.fileID,
                  })
                }
                ,fail:(err)=>{
                  console.log(err)
                  wx.showToast({
                    title: 'fail',
                    duration:1000,
                  })
                }
              })
            }else{
              console.log('err:获取文件失败')
                  wx.showToast({
                    title: 'fail',
                    duration:1000,
                  })
            }

          },fail:(err)=>{
            console.log(err)
            wx.showToast({
              title: 'fail',
              duration:1000,
            })
          },
        })
  },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值