参考多个资料和具体实践,决定使用pdfjs
下载地址:http://mozilla.github.io/pdf.js/getting_started/#download
下载完成后放到public/static目录下
具体使用
template:<iframe :src="pdfSrc" frameborder="0" style="width: 100%; height: 100%;"></iframe>
将通过request请求获取的pdf Blod数据流:
getData(url) {
const auth = JSON.parse(localStorage.getItem("auth") || null) || {};
const xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("token", auth.token);
xhr.responseType = "blob";
xhr.onload = function() {
if (xhr.status === 200) {
let content = xhr.response;
this.pdfTask(new Blob([content]));
} else {
return false;
}
};
xhr.send();
},
转换为url,method:
getObjectURL(file) {
let url = null;
if (window.createObjectURL != undefined) {
// basic
url = window.createObjectURL(file);
} else if (window.webkitURL != undefined) {
// webkit or chrome
try {
url = window.webkitURL.createObjectURL(file);
} catch (error) {
console.log(error);
}
} else if (window.URL != undefined) {
// mozilla(firefox)
try {
url = window.URL.createObjectURL(file);
} catch (error) {
console.log(error);
}
}
return window.origin + "/static/pdf/web/viewer.html?file=" + url;
}
本地测试:
template:<input type="file" @change="checkFile($event)" />
checkFile(event) {
const self = this;
let reader = new FileReader();
reader.onload = function() {
// 将返回的流数据转换为url
self.getObjectURL(new Blob([this.result]));
};
reader.readAsArrayBuffer(event.target.files[0]);
},
网友评论