JS-前端在dom中预览pdf等文件

1、将pdf等文件显示到dom元素中预览

  • pdf文件可以是blob、url、file类型等
  • 只要使用URL.createObjectURL(file)全部转为URL即可使用
  • 无需借助任何插件,只需要使用<object></object>标签即可实现

1.1、html

html 复制代码
<template>
  <div class="home">
    <object id="pdf-object" width="50%" height="500px"></object>
 
    <input type="file" id="pdf-file" />
    <button @click="showPDF">预览文件</button>
  </div>
</template>

1.2、js

js 复制代码
<script>

export default {
  name: 'HomeView',
  methods: {
    showPDF() {
      const inputElement = document.getElementById('pdf-file');
      const objectData = document.getElementById('pdf-object');

	  // 获取选择的文件
      const file = inputElement.files[0];
      // 转为url
      const url = URL.createObjectURL(file);
      // 给object标签赋值 相当于image标签的src属性
      objectData.data = url;
    }
  }
}
</script>

1.3、效果

1.4、注意

  • 如果不是这种file类型,而是后台返回的blob类型数据。
  • 那么在接收blob的时候,需要给构造函数传入第二个类型参数application/pdf,如下这样
  • 如果需要展示其他类型文件,只需修改相应type值即可。
  • word、excel、ppt等,不能直接展示,具体原因如下
相关推荐
kyriewen115 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
Timer@6 小时前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫6 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81637 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan8 小时前
FastAPI -API Router的应用
前端·网络·python
走粥9 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory0019 小时前
layui select重新渲染
前端·layui
weixin1997010801610 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化
九皇叔叔10 小时前
003-SpringSecurity-Demo 统一响应类
java·javascript·spring·springsecurity