~得空写一下~
技术栈:vue2+elementUI
1.新建组件previewFile.vue
<template>
<div :class="['dialog-box']">
<el-dialog
:title="`${file.title}文件预览`"
:visible.sync="file.dialogVisible"
:before-close="handleClose"
width=""
top="0"
>
<div>
<iframe
class="child"
frameborder="0"
:src="'http://view.xdocin.com/xdoc?_xdoc=' + file.fileurl"
:style="{ height: height }"
/>
</div>
</el-dialog>
</div>
</template>
<script>
export default {
props: {
file: {
type: Object,
default: function () {
return {
fileurl: "",
dialogVisible: false,
title: "",
};
},
},
},
data() {
return {
height: window.innerHeight - 120 + "px",
dialogVisible: false,
};
},
methods: {
handleClose() {
this.file.dialogVisible = false;
},
},
};
</script>
<style scoped>
.child {
width: 100%;
height: 100%;
border: 0;
}
.dialog-box >>> .el-dialog__headerbtn {
font-size: 24px;
top: 18px;
}
.dialog-box >>> .el-dialog__headerbtn .el-dialog__close {
color: #fff;
}
.analysis >>> .el-dialog {
left: 119px;
}
.analysis-dialog >>> .el-dialog {
left: 27px;
}
.dialog-box >>> .el-dialog {
width: 100%;
border-radius: 0px;
}
.dialog-box >>> .el-dialog .el-dialog__header {
background-color: #0094ff;
border-radius: 0;
}
</style>
2.引用组件
<template>
<div>
<div class="shadow-box" v-else>
<button @click="download(item)">下载</button>
<button @click="delFile(item, index)">删除</button>
<button @click="openFile(item, index)">预览</button>
</div>
<!-- 预览文件 -->
<preview-file :file="file" />
</div>
</template>
data:
file: {
fileurl: "",
dialogVisible: false,
title: "",
},
js:
// 打开客户文件
openFile(item, idx) {
let client = new OSS({
region: "oss-cn-shenzhen",
accessKeyId: this.ossSignature2.accessid,
accessKeySecret: "XXXX",
bucket: "XXXX",
});
let filename = item.fileName;
let response = {
"content-disposition": `attachment; filename=${encodeURIComponent(
filename
)};expires: 7200`,
};
let url = client.signatureUrl(item.filePath, {
response,
});//获取oss签名URL
// window.location.href = url;//下载
this.file.fileurl = encodeURIComponent(url)//后端请求回来的文件地址url--传给子组件
this.file.dialogVisible = true//弹窗--传给子组件
this.file.title = filename//文件名称--传给子组件
},
遇到的问题:
解决Mixed Content: The page at ‘https://xxxx‘ was loaded over HTTPS..
报错的的原因:查资料后发现原因是在https中请求http接口或引入http资源都会被直接blocked(阻止),浏览器默认此行为不安全,会拦截。
解决办法如下:(在index.html的head中加入以下代码)
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
加入该标签的原理是使用META标签强制将http请求转成https(SSL协议)请求