自学内容网 自学内容网

pdf的下载,后端返回工作流,前端进行转换

前端将后端返回的工作流进行转换

项目中接触到了pdf的下载和预览的功能,记录一下~
这里pdf的下载和预览的接口,后端返回的数据结构与其他的接口返回的数据结构有点不同,是直接返回的工作流,在控制台接口的响应预览内容大致是这样的
在这里插入图片描述
在使用下载预览功能的页面引入axios

<script>
import axios from 'axios
</script>

这里说明一下问什么要重新引入axios使用,为什么不使用封装好的axios

一般来说,项目中我们会对axios进行封装,在请求拦截器/响应拦截器中进行一些操作,通常响应回来的数据内容会被包裹在data中,因此会在响应拦截器中return时直接拿response.data.data,但后端返回工作流只包裹了一层data,如果直接用封装好的axios,则拿不到响应回来的数据内容,因此使用该功能的页面我们单独引入了axios进行使用

下载的方法

downloadPdf() {
      axios({
        url: '接口url',
        method: 'GET',
        responseType: 'blob', // important
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '下载文件.pdf');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }).catch(error => {
        console.error('Error fetching PDF:', error);
      });
    },

预览的方法

viewPdf() {
      axios({
        url: '接口url',
        method: 'GET',
        responseType: 'blob', // important
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }));
        //这里我是新打开一个浏览器窗口去预览文件,因为我尝试插入到body中,但是预览窗口没有关闭按钮,所以做的用新的浏览器窗口进行预览
        window.open(url)
      }).catch(error => {
        console.error('Error fetching PDF:', error);
      });
    }

原文地址:https://blog.csdn.net/weixin_46394325/article/details/140630331

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!