首页 > 解决方案 > axios POST 使用 blob 作为 responseType

问题描述

所以我试图通过 axios 和 blob 下载文件。问题是我需要传递密码,因此我不能使用“GET”请求。出于测试目的,我仍然发出“GET”请求让我开始。由于项目结束,我想最终解决这个问题,但我找不到解决方案。

那是我的工作代码,带有“GET”请求,可以给你一个想法。

                    axios({
                        url: `/api/download/?uuid=${uuid}&password=${password}`,
                        method: "GET",
                        responseType: "blob",
                    })
                    .then((response) => {

                        var fileURL = window.URL.createObjectURL(
                            new Blob([response.data])
                        );
                        var fileLink = document.createElement("a");

                        fileLink.href = fileURL;
                        fileLink.setAttribute("download", filename);
                        document.body.appendChild(fileLink);

                        fileLink.click();
                        self.showLottie = false;
                    })
                    
                    .catch(function (error) {

                        self.showLottie = false;

                        alert("Download failed");

                    });

标签: restpostdownloadaxiosblob

解决方案


好的,所以基本上我所要做的就是将 uuid 和密码放入 params 对象中。

  axios({
                        url: `/api/download`,
                        method: "GET",
                        responseType: "blob",
                        params: {
                                uuid,
                                password,
                                },
                    })
                    .then((response) => {

                        var fileURL = window.URL.createObjectURL(
                            new Blob([response.data])
                        );
                        var fileLink = document.createElement("a");

                        fileLink.href = fileURL;
                        fileLink.setAttribute("download", filename);
                        document.body.appendChild(fileLink);

                        fileLink.click();
                        self.showLottie = false;
                    })
                    
                    .catch(function () {

                        self.showLottie = false;

                        alert("Download failed");

                    });

说明: HTTPS URL 是否加密?


推荐阅读