Javascript - 下载从后端提供的 blob 格式的 xls 文件

问题描述 投票:0回答:1

我有一个用 Java 编写的后端服务,它将为 vue 前端应用程序提供支持。当后端提供文件时,我需要开始下载文件。目前我注意到提供文件的后端的响应是一个对象。该对象具有以下结构:

{
 data: "..." //This is supposed to be a blob
}

如何将响应正确转换为 xls 文件?我尝试将其传递给文件构造函数,但生成的文件似乎已损坏。

getXlsFile(data)
 .then( (res) => {
   let file = new File([res?.data], 'report.xls');
   ...
  })

不确定是否需要再次将响应转换为 blob 格式?

javascript file blob xlsx
1个回答
0
投票

您可以尝试使用javascript Blob进行转换,然后强制下载文件

这是我的 utils.js 中的一个工作函数(它从文本区域元素下载一个 txt 文件)

function generateTextFile(textareaElement, filenameWithoutExtension) {
    var textToWrite = textareaElement.val();
    var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
    var fileNameToSaveAs = filenameWithoutExtension + ".txt" //Your filename;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

你应该尝试这样的事情:(未经测试)

    var textFileAsBlob = new Blob([blobFromYourBackend], { type: 'application/vnd.ms-excel' });
    var fileNameToSaveAs = "myexcel.xls" //Your filename;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null) {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
© www.soinside.com 2019 - 2024. All rights reserved.