原生微信小程序批量上传文件

作者: hedeqiang

发布时间: 2020-01-11 15:41:19

开发微信小程序,可能遇到最蛋疼的一个问题就是 小程序不支持批量上传,一次只能上传一个文件。想要批量上传只能递归上传。通过以下方式即可实现 “批量上传”。

index.wxml

<!--index.wxml-->
<view class="container">
  <block wx:for="{{images}}" wx:key="*this">
    <view>
      <image src="{{item}}" bindtap="handleImagePreview"></image>
    </view>
  </block>
    <button bindtap="uploudImage"> 批量上传 </button>
</view>

index.js

//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    images:[],
  },
  onLoad: function () {
  },
  uploudImage() {
    const that = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log(res);
        that.setData({
          images: tempFilePaths,
        });
        var promise = Promise.all(tempFilePaths.map((tempFilePath, index) => {
          return new Promise(function (resolve, reject) {
            wx.uploadFile({
              url: 'uploadurl',
              filePath: tempFilePath,
              name: 'name',
              header: {},
              formData: {},
              success: function (res) {
                resolve(res.data);
              },
              fail: function (err) {
                console.log(err)
                reject(new Error('failed to upload file'));
              }
            });
          });
        }));
        promise.then(function (results) {
          console.log(results); //返回上传成功的数据
        }).catch(function (err) {
          console.log(err);
        });
      }
    })
  },
})

参考 微信小程序 官方文档

关于极客返利

极客返利 是由我个人开发的一款网课返利、返现平台。包含 极客时间返现、拉勾教育返现、掘金小册返现、GitChat返现。目前仅包含这几个平台。后续如果有需要可以考虑其他平台。 简而言之就是:你买课,我返现。让你花更少的钱,就可以买到课程。

https://geek.laravelcode.cn

https://geek.idaka.ink

版权许可

本作品采用 知识共享署名 4.0 国际许可协议 进行许可。

转载无需与我联系,但须注明出处,注明文章来源 原生微信小程序批量上传文件