首页 > 解决方案 > 如何在 ASP.NET Core 中使用客户端下载文件并做出反应?

问题描述

我有一个带有 ASP.NET Core 的项目并做出反应。我想单击在 docx 文件中生成和下载文本的按钮。

我在后端使用此代码:

    // Creates a new instance of WordDocument (Empty Word Document)
    using (WordDocument document = new WordDocument())
    {
        // Adds a section and a paragraph to the document
        document.EnsureMinimal();

        // Appends text to the last paragraph of the document
        document.LastParagraph.AppendText(text);
        MemoryStream stream = new MemoryStream();

        // Saves the Word document to  MemoryStream
        document.Save(stream, FormatType.Docx);
        stream.Position = 0;

        // Download Word document in the browser
        return File(stream, "application/msword", name + ".docx");
    }

我得到 docx 文件的保存对话框,但保存的文件已损坏(无法访问的内容)。

我在 ASP.NET MVC (razor) 示例中使用了上面的代码并且没问题。

我不知道客户端(反应)返回文件中的句柄。

标签: c#reactjsasp.net-core

解决方案


也许您的数据不是HTML格式。尝试下面的代码创建 Word 可以打开的正确 html 格式。

var name="myFile";
var text = `<html><body>${response.data}</body></html>`;
var blob = new Blob([text], { type: 'application/msword' });
var url = URL.createObjectURL(blob);
var link = document.createElement('A');
link.href = url;
link.download = `${name}.doc`;
link.click();

推荐阅读