c# - 如何在 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) 示例中使用了上面的代码并且没问题。
我不知道客户端(反应)返回文件中的句柄。
解决方案
也许您的数据不是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();
推荐阅读
- jenkins-pipeline - 我们如何使用 Jenkins Pipeline 在 Mac 代理中使用 Chamber
- c# - Windows 中的动态端口范围是全部保留还是每个目标端口保留?
- android - Android TV RecognizerIntent 适用于模拟器(Studio Studio 模拟器)但不适用于 ADT-3
- javascript - 遍历 dom 元素并将每个元素附加到其他元素
- c - Ceedling 使用错误的启动文件
- arrays - 使用scala apark检索存储在每一行的数据框列中的数组
- java - 如何在 Spring 中使用上传文件列表?
- c# - 实体框架,保存新数据库条目的问题
- android - Android - 阿拉伯语百分比字符的错误位置
- r - 计算每个类别的平均值,并用这个平均值填充缺失值