如何使用Asp.NetCore和Angular下载文件

时间:2019-01-21 13:32:30

标签: c# angularjs asp.net-core

我正在从WebPage用Excel开发报表。该页面在某些表中包含一些图表和一些数据。 我有一个Excel文件,它可以作为模型在文件内写入数据。我在工作表中创建了一些图表,然后在工作表中写入了数据,并引用了这些数据以在图表中使用它。一切正常,除了无法下载文件的事实。

我创建了一段代码来执行此操作,然后成功生成了文件。我现在要尝试的就是下载此文件。

所以我尝试了一些事情:

因此,我生成了该文件,并生成了已下载的文件,但已损坏。

API

var mimeType = "application/vnd.ms-excel";

string file = Path.Combine(path, fileName);

var memory = new MemoryStream();

using (var stream = new FileStream(file, FileMode.Open))
{
    stream.CopyTo(memory);
}

memory.Position = 0;

return File(memory, mimeType, "filename.xlsx");

角度

return $http.post(url, data, config)
    .then(function (response) {

    //TODO: Implementar o download do arquivo
    var file = new Blob([data], { type: 'application/vnd.ms-excel' });
    saveAs(file, 'filename.xlsx');

    }).catch(function (error) {
        console.log("error");
    });

1 个答案:

答案 0 :(得分:0)

该行似乎有错误

var file = new Blob([data], { type: 'application/vnd.ms-excel' });

尝试将其更改为

var file = new Blob([response.data], { type: 'application/vnd.ms-excel' });

还可以尝试以下代码。效果很好

var linkElement = document.createElement('a');
try {
    var blob = new Blob([response.data], { type: 'application/vnd.ms-excel'});
    var url = window.URL.createObjectURL(blob);

    linkElement.setAttribute('href', url);
    linkElement.setAttribute("download", filename);

    var clickEvent = new MouseEvent("click", {
        "view": window,
        "bubbles": true,
        "cancelable": false
    });
    linkElement.dispatchEvent(clickEvent);

    } 
    catch (ex) {
        console.log(ex);
    }

来源:http://jaliyaudagedara.blogspot.com/2016/05/angularjs-download-files-by-sending.html