在 Blazor 中创建和下载 Word 文件

Create and download Word file in Blazor

我正在尝试创建一个 Word 文件并在客户端浏览器中下载创建的文件。

创建部分似乎工作正常,我可以从文件夹中手动打开文件。 但是浏览器中下载的文件无法正确打开并产生错误 “文件已损坏,无法打开”

我正在使用这里的代码 Microsoft instructions for downloading a file in Blazor

我的代码是这样的

 private async Task CreateAndDownloadWordFile()
{
    var destination = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    var fileName = destination + "\test12.docx";
    //SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(destination, SpreadsheetDocumentType.Workbook);
    using (WordprocessingDocument doc = WordprocessingDocument.Create
(fileName, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
    {
        // Add a main document part.
        MainDocumentPart mainPart = doc.AddMainDocumentPart();

        // Create the document structure and add some text.
        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());
        Paragraph para = body.AppendChild(new Paragraph());
        Run run = para.AppendChild(new Run());

        // String msg contains the text, "Hello, Word!"
        run.AppendChild(new Text("New text in document"));

    }
    var fileStream = GetFileStream();
    using var streamRef = new DotNetStreamReference(stream: fileStream);
    await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);

}



private Stream GetFileStream()
{
    var randomBinaryData = new byte[50 * 1024];
    var fileStream = new MemoryStream(randomBinaryData);

    return fileStream;
}

我使用这个 Javascript 代码

async function downloadFileFromStream(fileName, contentStreamReference) {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);

triggerFileDownload(fileName, url);

URL.revokeObjectURL(url);
}

function triggerFileDownload(fileName, url) {
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
}

有什么想法吗?

But the downloaded file in browser does not open correctly

那可能是因为你

  1. 首先创建一个Word文档
  2. 然后下载var randomBinaryData = new byte[50 * 1024];

the downloaded file in browser

检查那些。它们正好是 50 * 1024 字节吗?

--

此外,您不应将完整的 C:\... 路径传递给下载功能。

  var fileStream = File.OpenRead(filename);
  using var streamRef = new DotNetStreamReference(stream: fileStream);
//await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
  await JS.InvokeVoidAsync("downloadFileFromStream", "suggestedName", streamRef);