vue---- H5页面 pdf,docx,excel文件预览&&下载功能
pdf,docx,excel文件预览&&下载适用于vue2和vue3,示例为vue3
1.npm下载这些文件的插件(选择自己需要预览的进行下载)
javascript
安装pdf组件
npm install @vue-office/pdf vue-demi
安装docx组件
npm install @vue-office/docx vue-demi
安装excel组件
npm install @vue-office/excel vue-demi
2.页面渲染完整代码,包含了预览和下载的功能
javascript
<template>
<view class="h-[100%] w-[100%]">
<view class="mb-[100rpx] absolute">
<top-nav
title="预览"
backShow
:sheetShow="true"
nameIcon="download"
@sheetShowBtn="download"
>
<text class="text-[#333333] text-[28rpx]">下载</text>
</top-nav>
</view>
<view class="h-[99vh] w-[100%] relative pt-[50px]">
<view class="w-[100%] h-[100%]">
<vue-office-pdf :src="url" v-if="type == 'pdf'" />
<vue-office-docx :src="url" v-if="type == 'docx' || type == 'doc'" />
<vue-office-excel :src="url" v-if="type == 'xlsx' || type == 'xls'" />
</view>
<!-- <iframe
:src="'http://www.pfile.com.cn/api/profile/onlinePreview?url=' + url"
style="width: 100%; height: 100%; border: none; margin-top: 50px"
></iframe> -->
</view>
</view>
</template>
<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import VueOfficePdf from '@vue-office/pdf'
import VueOfficeDocx from '@vue-office/docx'
import VueOfficeExcel from '@vue-office/excel'
import '@vue-office/excel/lib/index.css'
import '@vue-office/docx/lib/index.css'
const url = ref('') // 文件地址
const attach_name = ref('') // 文件名
const type = ref('') // 文件类型
onLoad((options) => {
url.value = decodeURIComponent(options.url!)
attach_name.value = options.name
type.value = options.type
console.log(attach_name.value)
})
/**
* @description: 点击下载按钮
* @return {*}
*/
const download = () => {
downloadFile(url.value, attach_name.value)
}
/**
* @description: 下载文件
* @param {*} url 链接地址
* @param {*} fileName 文件名
* @return {*}
*/
async function downloadFile(url, fileName) {
try {
const response = await fetch(url)
if (!response.ok) {
throw new Error('文件下载失败,状态码: ' + response.status)
}
// 将响应内容转换为 Blob
const blob = await response.blob()
// 创建 Blob URL
const blobUrl = URL.createObjectURL(blob)
// 创建一个隐藏的 <a> 标签
const link = document.createElement('a')
link.href = blobUrl
link.download = fileName // 设置文件名
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
// 释放 Blob URL
URL.revokeObjectURL(blobUrl)
console.log('文件下载成功:', fileName)
} catch (error) {
console.error('文件下载失败:', error)
}
}
</script>
示例图片: