【问题标题】:How to download file with client in ASP.NET Core and react?如何在 ASP.NET Core 中使用客户端下载文件并做出反应?
【发布时间】:2020-02-02 14:39:33
【问题描述】:

我有一个使用 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) 示例中使用了上面的代码并且没问题。

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

【问题讨论】:

  • 您是否尝试关闭文档(document.close())然后返回流?即使您可以尝试在 using 块之外返回文档....
  • @Mark 不,我没有关闭文档。后端的所有代码就是它。注意,我使用 Syncfusion.DocIO.Net.Core nuget

标签: c# reactjs asp.net-core


【解决方案1】:

也许您的数据不是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();

【讨论】:

    猜你喜欢
    • 2019-09-01
    • 2020-08-31
    • 2019-08-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多