后端返回文件流,前端用blob转换后,下载的文件乱码或者打不开怎么解决

1、确认接口有没有设置 responseType: “blob”
2、使用blob转换,res 是 后端返回的文件流

export function exportFile(res, filename) {
    
    
    if (!res) {
    
    
        return
    }
    const blob = new Blob([res.data]);
    let url = window.URL.createObjectURL(blob);
    if ("download" in document.createElement("a")) {
    
    
        try {
    
    
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", filename);
            document.body.appendChild(link);
            link.click();
            link.remove()
        } catch (e) {
    
    
            console.log(e)
        }
    } else {
    
    
        navigator.msSaveBlob(blob, filename);
    }
}

3、如果文件还是打不开,提示文件格式不对……,那就看看项目中有没有引用mockJs,有的话注释掉就可以啦

猜你喜欢

转载自blog.csdn.net/lala1091/article/details/127126773