1.POST 方法下载实现原理

通过 fetch 请求获取文件,然后利用Blob 对象来接收处理,在接收到后端返回的文件后,把其转化一下,放入a标签的href中,并触发下载行为。获取异常时,返回json数据并弹窗警告。

实现的代码如下

        async function post_download(url, params) {
            const request = {
                body: JSON.stringify(params),
                method: "POST",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8"
                }
            }

            const response = await fetch(url, request);
            try {
                const filename = response.headers.get("content-disposition").split(";")[1].split("=")[1];
                const blob = await response.blob();

                const link = document.createElement("a");
                link.download = decodeURIComponent(filename);
                link.style.display = "none";
                link.href = URL.createObjectURL(blob);
                document.body.appendChild(link);
                link.click();
                URL.revokeObjectURL(link.href);
                document.body.removeChild(link);
            } catch (e) {
                response.json().then(data => {
                    if (!data["result"]) {
                        alert(data["msg"]);
                    }
                })
            }
        }

Related Posts