使用axios vuejs下载的Excel文件已损坏

时间:2020-01-07 07:48:16

标签: javascript excel vue.js axios blob

我正在尝试下载Excel文件。我已经使用axios。

我尝试了以下代码

     axios.post(backendURL + 'api/client?file_name='+file_name,params, {
        file_name: file_name
    }, {
        responseType: 'blob'
    }).then((response) => {
        const url = URL.createObjectURL(new Blob([response.data], {
            type: 'application/vnd.ms-excel'
        }))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', file_name)
        document.body.appendChild(link)
        link.click()
    });

我收到错误消息,因为“ Excel无法打开文件“ filename.xlsx”,因为文件格式或文件扩展名无效。请验证文件未损坏且文件扩展名与文件格式匹配“

我尝试了所有在google中找到的解决方案,但没有任何效果。请帮忙

1 个答案:

答案 0 :(得分:-1)

  downloadFile() {
            axios({
                url: this.scenario.file,  //.substring(0, this.scenario.file.lastIndexOf("/"))
                method: "GET",
                headers: {"Accept": "application/vnd.ms-excel"},
                responseType: "blob"
            }).then(response => {
                const fileURL = window.URL.createObjectURL(new Blob([response.data]));
                const fileLink = document.createElement("a");

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

                fileLink.click();
            });
        },
相关问题