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讲解比较详细