vue:遇到的坑之----预览、下载文件
预览:后台返回文件流,前端通过pdf.js来实现文件预览。pdf.js要修改的配置,其他博主都写的很详细了,我就不叙述了。就贴上预览的前端代码,更直观的看代码1、点击预览,弹出预览对话框(通过iframe实现)html:这里的:src的值是固定要这么写的,不然pdf插件会找不到文件路径,因此预览不了<el-button size="mini" @click="p...
·
预览:
后台返回文件流,前端通过pdf.js来实现文件预览。
pdf.js要修改的配置,其他博主都写的很详细了,我就不叙述了。就贴上预览的前端代码,更直观的看代码
1、点击预览,弹出预览对话框(通过iframe实现)
html:这里的:src的值是固定要这么写的,不然pdf插件会找不到文件路径,因此预览不了
<el-button size="mini" @click="previewFiles(scope.row)"> 预览</el-button>
<el-dialog
:visible.sync="dialogVisible4preview"
fullscreen
:close-on-click-modal="false"
>
<iframe id='previewPdf' :src="'/static/pdf/web/viewer.html?file=' + previewFileUrl" height="560" width="100%">
</iframe>
</el-dialog>
data:
dialogVisible4preview:false,
previewFileUrl:"",
js: baseURL是基准路径,后面加上需要带上的参数和token,如果文件后面本身就带文件名称加后缀的话,后面的&.pdf可以不用加
// 预览文件
previewFiles(obj) {
this.dialogVisible4preview = true;
let url = baseURL + `xxxx/xxxx/preview?fileId=${obj.id}&token=${this.$store.state.token}&.pdf`
this.previewFileUrl = encodeURIComponent(url)
},
2.点击预览,弹出新窗口实现预览 (跟第一种大同小异)
html:
<el-button @click="previewFiles(scope.row)">预览</el-button>
js:
// 预览文件
previewFiles(obj) {
let url = baseURL + `xxxx/xxxx/preview?fileId=${obj.id}&token=${this.$store.state.token}`
window.open('/static/pdf/web/viewer.html?file=' + encodeURIComponent(url) )
},
注意:我的路径中携带token是为了解决跨域问题,后台也相应做了修改,所以这里不是必须带的参数
如果采用第一种方法的话,可以给大家介绍一个弹框插件layer.js,具体写法放在以后有时间补充
下载:
我封装在了全局里,方便所有页面使用
Vue.prototype.download = (data, fileName) =>{
if (!data) {
return;
}
let url = window.URL.createObjectURL(
new Blob([data], { type: "application/octet-stream" })
);
let link = document.createElement("a");
link.style.display = "none";
link.href = url;
link.setAttribute("download", fileName);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url); // 释放URL 对象
};
使用的时候直接引用
// 下载文件
downloadFile(obj) {
this.$axios.post( url,{fileId: obj.id},{responseType: "blob"}).then(res => {
this.download(res.data, obj.fileName);
});
},
-------------
文件名乱码:
//下载流文件名乱码转换
Vue.prototype.convertUtf8 = (str)=>{
// 将乱码数据转换为字节数组
var ch, st, re = [];
for (var i = 0; i < str.length; i++ ) {
ch = str.charCodeAt(i);
st = [];
do {
st.push( ch & 0xFF );
ch = ch >> 8;
}
while ( ch );
re = re.concat( st.reverse() );
}
// 将字节数组转换为utf-8格式字符串
if(typeof re === 'string') {
return re;
}
var retStr = '',
_arr = re;
for(var i = 0; i < _arr.length; i++) {
var one = _arr[i].toString(2),
v = one.match(/^1+?(?=0)/);
if(v && one.length == 8) {
var bytesLength = v[0].length;
var store = _arr[i].toString(2).slice(7 - bytesLength);
for(var st = 1; st < bytesLength; st++) {
store += _arr[st + i].toString(2).slice(2);
}
retStr += String.fromCharCode(parseInt(store, 2));
i += bytesLength - 1;
} else {
retStr += String.fromCharCode(_arr[i]);
}
}
// 返回
return retStr;
};
有问题欢迎指出~
更多推荐
已为社区贡献7条内容
所有评论(0)