纯借鉴
纯前端预览文档功能。这个功能比较常见,大多数小白就是下载相对应格式的插件。再进行判断显示就显得很麻烦(我就是那个小白)。
然后发现了这个插件 officeToHtml 这个真的舒服。不过也不是所有的格式都会显示。直接上代码
我这里用的是pnpm下载的
pnpm add --save file-viewer3
下载好之后封装起来:(注释起来的是我用不到的,用不用看个人需求);
<script setup lang="ts">
import { computed, nextTick, onMounted, ref } from "vue";
const props = defineProps<{
url?: string,
file?: File,
name?: string,
}>()
// iframe引用
const frame = ref<HTMLIFrameElement>();
// iframe路径指向构建产物,这里是/,因为放在了public下面
// 如果使用cdn,请使用http://viewer.flyfish.group
const source = '/file-viewer3/index.html'
// 查看器的源,当前示例为本源,指定为location.origin即可
const viewerOrigin = location.origin;
// 构建完整url
const src = computed(() => {
// 文件名称,建议传递,提高体验性
const name = props.name || '';
// console.log("props", props.url)
// return props.url
// if (props.url) {
// 直接拼接url
return `http://localhost:5220/${props.url}`
// } else if (props.file) {
// // 直接拼接来源origin
// return `${source}?from=${encodeURIComponent(viewerOrigin)}&name=${encodeURIComponent(name)}`
// } else {
// return source;
// }
})
// 发送文件数据
// const sendFileData = () => {
// nextTick(() => {
// const viewer = frame.value;
// if (!viewer || !props.file) return;
// viewer.onload = () => viewer.contentWindow?.postMessage(props.file, viewerOrigin);
// })
// }
onMounted(() => {
// sendFileData();
})
</script>
<template>
<iframe title="文档预览" ref="frame" :src="src" class="iframe-viewer" />
</template>
<style scoped>
.iframe-viewer {
height: 500px;
width: 100%;
border: 0
}
</style>
在需要用到的页面调用就ojbk了
// 引入
import FileView from "@/components/viewer3/index.vue";
// 调用
<file-view :url="sources?.url" />
就搞定!
借鉴地址1:纯前端文档预览,还要支持所有主流格式,有这一篇就足够了_前端文件预览_小爬的老粉丝的博客-优快云博客借鉴地址:
基于Vue3+TypeScript+Vite实现的文件在线预览 file-viewer3使用指南_vue预览txt文件_小爬的老粉丝的博客-优快云博客