`
musicbox95351
  • 浏览: 221228 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

在前端拿到后端传回的pdf文件的byte数组后展示到浏览器

 
阅读更多
这里是一个vue的实现方式,其它方式应该也差不多。
总体思路是请求后端,由后端返回一个pdf文件的byte[],前端拿到数据后,在前端判断文件类型并将byte数组转换成客户端的文件并返回一个文件URL给hmlt标签。

html标签部分-----------------------------------------------------------------
<div>
                    <img :src="erptUrl" />
                    <object :data="erptPdfUrl" type="application/pdf" width="750px" height="750px">
                    <embed :src="erptPdfUrl" type="application/pdf">
                        <p>This browser does not support PDFs. Please download it..</p>
                    </embed>
                </object>
                </div>

js部分----------------------------------------------------------------------------------

......
data:{
erptUrl:  null,//图片显示URL
                erptPdfUrl: null,//PDF显示URL
}
......

let MIMETYPES = {
                   
                    'pdf': 'application/pdf',
                    'jpeg': 'image/jpeg',
                    'jpg': 'image/jpeg',
                    'jpe': 'image/jpeg',
                    'bmp': 'image/bmp',
                   
                };
let config = {
                    method: 'post',
                    headers: { 'Content-Type': 'application/json;charset=UTF-8' },
                    responseType: 'blob'
                };

return new Promise((resolve, reject) => {
                    axios
                        .post('请求后台的URL', {请求后台的参数对象}, config)
                        .then(res => {
                            let contentDisposition = res.headers['content-disposition'];
                            if (!contentDisposition) {
                                MessageBox.error('错误信息提示');
                                return;
                            }
                            var reg = new RegExp('filename=([^;]+\\.[^\\.;]+);*');
                            var result = reg.exec(contentDisposition);
                           
                            let fileType = result[1].split('.')[1];
                            let blob = new Blob([res.data], {
                                type: MIMETYPES[fileType] || '.txt'
                            });
                           
    //这里如果判断为pdf文件则用<object><embed></embed></object>展示
                            if(fileType == 'pdf'){
                                this.erptPdfUrl = window.URL.createObjectURL(blob,true);//该方法将生成本地文件并返回一个本地URL
                            }else{
                                this.erptUrl = window.URL.createObjectURL(blob,true);
                            }
                              
                           
                        })
                        .catch(err => {
                            reject(err);
                        });
                });
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics