微信小程序之图片上传功能

一、效果演示

二、源代码

由于是使用的组件,所以图片没有wxss样式设置,需要根据我的项目demo,配置一下组件环境。

study.wxml

<form onsubmit="uploadImgs">
  <view class="cu-bar bg-white margin-top">
    <view class="action">
      图片上传
    </view>
    <view class="action">
      {{imgList.length}}/{{imgMaxNumber}} 
    </view>
  </view>

  <view class="cu-form-group">
    <view class="grid col-4 grid-square flex-sub">
      <view class="bg-img" wx:for="{{imgList}}" wx:key="index" bindtap="ViewImage" data-url="{{imgList[index]}}">
        <image src='{{imgList[index]}}' mode='aspectFill'></image>
        <view class="cu-tag bg-red" catchtap="DelImg" data-index="{{index}}">
          <text class="cuIcon-close"></text>
        </view>
      </view>
      <view class="solids" bindtap="ChooseImage" wx:if="{{imgList.length<imgMaxNumber}}">
        <text class="cuIcon-cameraadd"></text>
      </view>
    </view>
  </view>

  <view class="cu-bar bg-white">
    <button class='submit bg-brown margin-top margin-bottom' form-type='submit'>提交</button>
  </view>

</form>

study.js

// pages/study/study.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // imgList用于存储本地图片的临时地址 形如:http://tmp/0sxx3zbIXXMm5bbb7099a9b44038c251e42cdc99308e.png
    imgList: [],
    // imgMaxNumber用于控制图片上传的数量
    imgMaxNumber: 2
  },

  // 选择图片功能
  ChooseImage() {
    wx.chooseImage({
      count: this.data.imgMaxNumber, // 默认最大上传的图片数量为2张
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => { //下列代码相当于实现选中多张图片的功能
        // 判断imgList中是否有图片的临时地址 若有则将新的图片地址列表合并进imgList列表中  
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else { //否则将imgList设置为图片地址列表
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  // 图片预览功能
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  // 删除图片功能
  DelImg(e) {
    wx.showModal({
      title: '确定删除这张图片吗?',
      cancelText: '再看看',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },
  // 上传图片到服务器函数
  uploadPhoto() {
    // 判断用户是否选择了图片
    if (this.data.imgList.length>=1)
    {
      return new Promise((resolve,reject)=>{
        wx.uploadFile({
          url: 'http://xxxxx', //仅为示例,非真实的接口地址
          filePath: this.data.imgList[0],                  //要传的图片路径 这里只上传了imgList中的第一张图片
          header:{"authorization":"Bearer "+wx.getStorageSync('token')},
          name: 'file',                                //获取图片二进制文件的key
          formData: {                                  //其他需要携带的参数
            'user': 'test'
          },
          success (res){
            console.log(res.data);
            wx.showToast({
              title: '上传图片成功',
              icon: 'success'
            })
            resolve(res.data);
          }
        })
      })
    }
    else{
      wx.showToast({
        title: '请先选择图片',
        icon: 'error'
      })
      return;
    }
  },
  // 绑定提交按钮
  async uploadImgs() {
    // console.log(this.data.imgList);
    try {
      wx.showLoading({
        title: '上传中'
      })
      // 上传图片到服务器
      let res = await this.uploadPhoto();
      wx.hideLoading();
      console.log("res",res)
    } catch (error) {
      ()=>{
        wx.hideLoading()
        wx.showToast({
          title: '上传图片错误',
          icon: 'error'
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

三、项目demo地址

项目的github地址点击跳转,欢迎各位浏览和star✨。

四、参考链接

本项目是对项目Miniprogram-Picture-Upload的实现,对大佬的代码只进行了一点点的修改。

微信小程序实现授权登录之获取用户信息

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

布兹学长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值