<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:
text-align: left;
font-style: normal;
text-transform: none;
}
</style>