下载文件

323 阅读1分钟

下载文件

1、请求成功时返回的是一个流形式的文件,并且下载文件,需要设置responseType: ‘blob’或‘arraybuffer’,
2、但是请求失败的时候返回的是json ,需要用默认的responseType: 'json’来处理错误信息

那么我该怎么根据服务器响应后才设置这个responseType?

解决办法

axios设置 responseType: ‘blob’

        // axios封装
        Export(params) {
            return axios.get(`${baseURl}/user/export`, {
                params,
                responseType: "blob",
            });
        },
        
        // 请求下载
        const res = await Export(params)

        const reader = new FileReader()
        reader.readAsText(res, "utf-8")//解决乱码
        
        reader.addEventListener("loadend", () => {
            try {
                // 当请求正常时,json解析会出错,就会走catch
                const response = JSON.parse(reader.result)
                if(response.status && response.status != 200){
                    this.$message({
                        type: "error",
                        message: response.message,
                    });
                }
            } catch (err) {
                    const link = document.createElement("a");
                    const blob = new Blob([res]);
                    link.style.display = "none";
                    link.href = URL.createObjectURL(blob);
                    // download属性,当点击的时候弹出系统下载保存弹框
                    link.setAttribute("download", "下载.xlsx");
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    //如果想表明不再使用某个对象 URL,则可以把它传给 window.URL.revokeObjectURL()
                    window.URL.revokeObjectURL(link.href)
            }
        })

补充

  • 前端下载文件更好得办法是让后端直接返回文件的路径

  • location.href = url,调用浏览器下载,不然文件过大的时候,采用上述方式可能会内存溢出页面崩溃