前端新开页打开本直接下载的pdf和html后缀文件

124 阅读1分钟

直接打后端返回的接口,可以实现直接在浏览器下载对应文件

但是无奈产品觉得下载之后还要再手动点击打开,会影响用户的操作体验

所以就有了直接新开页面直接打开的需求

实现原理 (1)通过blob的格式接收后端传递过来的数据 (2)将数据用Blob对象转成blob格式 (3)再通过createObjectURL方法将blob数据转化为url (4)而后就可以直接通过url查看文件内容啦

import axios from "axios";
export default async function getDownload(url) {
    let res;
    try {
        res = await axios({
            method: "post",
            url: url,
        });
    } catch (e) {
        console.log("e:", e);
    }
    if (!(res.data && res.data.status_msg === "附件不存在")) {
        axios({
            method: "get",
            url: url,
            responseType: "blob",
        })
            .then((res) => {
                // const link = document.createElement("a");
                let blob = new Blob([res.data], {
                    type: "application/pdf;chartset=UTF-8",
                });
                let fileUrl = URL.createObjectURL(blob);
                window.open(fileUrl)
                
            })
            .catch((error) => {
                console.log(error);
            });
    } else {
        console.log("附件不存在");
    }
}