Vue 图片、PDF预览(Blod数据类型)

Vue 图片、PDF预览(Blod数据类型)

简单的PDF/图片预览

请求接口

需要将后端返回的文件转为文件流
这里的请求用的axios封装的 也可以用原生的 注意设置responseType: "blob"

axios.request({
	headers: { "content-type": "multipart/form-data" },
	  url: URL,//请求数据的接口 这里根据个人需求修改
	  method: "get",
	  withCredentials: true,
	  timeout: 120000,//请求响应时间
	  responseType: "blob"//MDN api参考 https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/responseType
	}).then(function(response) {
	  let reader = new window.FileReader();
	  let data = response.data || JSON.parse(response.request.responseText);
	  reader.readAsArrayBuffer(data);
	  reader.onload = function(e) {
	    const result = e.target.result;
	    // const contentType = data.type;
	    // 生成blob图片/PDF,需要参数(字节数组, 文件类型)
	    const blob = new Blob([result], { type: "application/pdf" });
	    // 使用 Blob 创建一个指向类型化数组的URL 
	    //MDN api参考 https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
		try {
	        that.pdfUrl = window.URL.createObjectURL(blob);
	    } catch (error) {
	        console.log(error);
	    }
  	};
}).catch(() => {
  this.$message.error("预览失败!");
});

html

 <div :style="{ height: '80vh', minHeight: '600px', margin: '8px 0px' }">
  <iframe
    :src="pdfUrl"
    id="previewPdf"
    frameborder="0"
    style="width: 100%; height: 100%"
  ></iframe>
</div>

图片预览

参考:点击链接 MDN讲解比较详细
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值