uniapp微信小程序-上传文件(支持图片和其他文件等),一次性获得最终返回值

uniapp-微信小程序-上传文件

<!-- 上传文件(自定义文件类型) -->
<template>
  <view class="upload-file-contarner" @click="handleUploadFile"> + </view>
</template>

<script>
export default {
  components: {},
  props: {
    //接受的附件格式
    types: {
      type: String,
      default: () => '.png,.jpg,.jpeg,.pdf,.doc,.docx,.xls,.xlsx',
    },
    //最多上传几个文件
    maxFile: {
      type: Number,
      default: 5,
    },
  },
  data() {
    return {};
  },
  methods: {
    handleUploadFile() {
      const types = this.types.split(',');
      //由于平台提供的方法只兼容app和H5,所以微信小程序使用该方法,唤起微信聊天框选择文件
      wx.chooseMessageFile({
        count: this.maxFile, //默认100
        extension: types,
        success: async (res) => {
          const files = res.tempFiles;
          const processResultFiles = async () => {
            const promise = files.map(async (v) => {
              return await this.asyncResultFiles(v);
            });
            return await Promise.all(promise);
          };
          //最终我们需要的接口返回的数据集合
          const processArr = await processResultFiles();
          this.$emit('handleUploadFile', processArr);
        },
        fail: (err) => {
          // 用户取消选择文件或选择文件失败的回调函数
          throw err;
        },
      });
    },
    //异步配合Promise.all可以一次性拿到最终的结果
    asyncResultFiles(item) {
      return new Promise(async (resolve) => {
        const result = await this.uploadFilePromise(item.path);
        const res = JSON.parse(result);
        if (res.code === '00000') {
          resolve(res.data);
        }
      });
    },
    //异步返回接口的结果
    uploadFilePromise(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          // #ifndef H5
          url: `${process.env.VUE_APP_BACK_URL}/nqi/file/uploadTopfs`,
          // #endif
          // #ifdef H5
          url: `${process.env.VUE_APP_BASE_URL}/nqi/file/uploadTopfs`,
          // #endif
          filePath: filePath,
          name: 'file',
          header: {
            'top-token': uni.getStorageSync('top-token'),
          },
          success: (res) => {
            resolve(res.data);
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },
  },
};
</script>
<style scoped lang="scss">
.upload-file-contarner {
  cursor: pointer;
  width: 100%;
  height: 80rpx;
  font-size: 50rpx;
  text-align: center;
  line-height: 80rpx;
  border: 1px solid $u-light-color;
  color: $u-light-color;
  margin-bottom: 20rpx;
  margin-top: 20rpx;
}
</style>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值