uniapp 小程序下载pdf组件封装

<template>
  <view v-if="downloadUrl" class="ty-download" @click="download">{{ downloadText }} </view>
</template>
<script>
export default {
  name: "ty-download",
  props: {
    downloadText: { type: String, default: "点击下载" },
    downloadUrl: { type: String, default: "" },
    fileType: { type: String, default: "pdf" },
  },
  data() {
    return { isDownloading: false, progress: 0 };
  },
  methods: {
    download() {
      if (!this.downloadUrl) {
        uni.showToast({
          title: "下载地址为空",
          icon: "none",
        });
        return;
      }
      if (this.isDownloading) return;
      this.isDownloading = true;
      uni.downloadFile({
        url: this.downloadUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            // 预览pdf文件
            uni.openDocument({
              filePath: res.tempFilePath,
              fileType: this.fileType,
              showMenu: true, // 右上角菜单,可以进行分享保存pdf
              success: () => {
                console.log("PDF预览成功");
              },
              fail: (err) => {
                uni.showToast({
                  title: "PDF预览失败:" + err.errMsg,
                  icon: "none",
                });
              },
            });
          } else {
            this.handleError("下载失败: HTTP " + res.statusCode);
          }
        },
        fail: (err) => {
          this.handleError("请求失败: " + err.errMsg);
        },
        complete: () => {
          this.isDownloading = false;
        },
      });
    },
    handleError(msg) {
      uni.showToast({
        title: msg,
        icon: "none",
      });
      this.$emit("error", msg);
    },
  },
};
</script>
<style scoped lang="scss">
.ty-download {
  display: inline-flex;
  font-family: PingFang SC, PingFang SC;
  font-weight: 400;
  font-size: 28rpx;
  color: #3e61ff;
  text-align: left;
  font-style: normal;
  text-transform: none;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值