背景: 因为某些oss云服务器 返回的资源链接,直接浏览器去访问都是会强制 下载的,包括一些 浏览器可以打开的资源 也是 ,例如 pdf。
思路:直接访问 就强制下载了,那我们就把数据抓下来 转流后再打开流来实现查看,
核心代码
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = () => {
console.log(206666, xhr);
if (xhr.status === 200) {
const blob = new Blob([xhr.response], { type: 'application/pdf' });
const a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// const blob = xhr.response;
// const fileURL = URL.createObjectURL(blob);
// window.open(fileURL);
}
};
xhr.send();
封装
// handOnlineView 在线查看
handOnlineView(file) {
const onlineViewFile = (url) => {
if (url) {
// 获取文件格式
const getFileFormatFun = (getFileFormatFunUrl) => {
const fileFormatStr = getFileFormatFunUrl.substr(getFileFormatFunUrl.lastIndexOf('.') + 1);
return fileFormatStr;
};
// if (getFileFormatFun(url) === 'pdf') {
if (['pdf', 'png', 'jpg'].includes(getFileFormatFun(url))) {
console.log(199999, url);
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = () => {
console.log(206666, xhr);
if (xhr.status === 200) {
let blobType = '';
if (getFileFormatFun(url) === 'pdf') {
blobType = 'application/pdf';
}
if (['png', 'jpg'].includes(getFileFormatFun(url))) {
blobType = 'image/jpeg';
}
const blob = new Blob([xhr.response], { type: blobType });
const objectURL = window.URL.createObjectURL(blob);
window.open(objectURL, url, 'width=1100,height=768');
window.URL.revokeObjectURL(objectURL);
// const a = document.createElement('a');
// a.href = window.URL.createObjectURL(blob);
//
// console.log(218888, a.href);
// a.target = '_blank';
// document.body.appendChild(a);
// a.click();
// document.body.removeChild(a);
// const blob = xhr.response;
// const fileURL = URL.createObjectURL(blob);
// window.open(fileURL);
}
};
xhr.send();
return false;
}
if (['doc', 'docx', 'xlsx', 'xls'].includes(getFileFormatFun(url))) {
const officeUrl = `https://view.officeapps.live.com/op/view.aspx?src=${url}`;
window.open(officeUrl, url, 'width=1100,height=768');
console.log(18666, officeUrl);
} else {
window.open(url, url, 'width=800,height=700');
}
} else {
console.error('缺少查看文件地址', url);
}
};
onlineViewFile(file.url);
},