简体   繁体   English

Blazor 下载 XML 文件 Javascript 报错

[英]Blazor Download XML File with Javascript Error

I generated a XML file with my application and I try to download it thanks to javascript in the client side of the blazor WebAssembly.我用我的应用程序生成了一个 XML 文件,我尝试下载它,感谢 blazor WebAssembly 客户端的 javascript。

I used the method gave by Microsoft with the XDocument saved in a Memory Stream:我用的是微软给的方法,XDocument保存在一个Memory Stream中:

async Task DownloadFileFromStream(MemoryStream Stream,string Name)
{

    var fileStream = Stream;
    var fileName = Name + ".xml";

    using var streamRef = new DotNetStreamReference(stream : fileStream);

    await JS.InvokeVoidAsync("downloadFileFromStream",fileName, streamRef);
}

and the javascript function associated with it in my index.html file:以及我的 index.html 文件中与之关联的 javascript function:

<script type="text/javascript">
    window.downloadFileFromStream = async (fileName, contentStreamReference) => {
        const arrayBuffer = await contentStreamReference.arrayBuffer();
        const blob = new Blob([arrayBuffer]);
        const url = URL.createObjectURL(blob);
        const anchorElement = document.createElement('a');
        anchorElement.href = url;
        anchorElement.download = fileName ?? '';
        anchorElement.click();
        anchorElement.remove();
        URL.revokeObjectURL(url);
    }
</script>

But each time the InvokeVoidAsync is called this error is displayed:但是每次调用 InvokeVoidAsync 时都会显示此错误:

Microsoft.JSInterop.JSException: Failed to fetch
TypeError: Failed to fetch
at Microsoft.JSInterop.JSRuntime. 
 <InvokeAsync>d__16`1[[Microsoft.JSInterop.Infrastructure.IJSVoidResult, 
  Microsoft.JSInterop, Version=6.0.0.0, Culture=neutral,  
PublicKeyToken=adb9793829ddae60]].MoveNext()
 at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String 
 identifier, Object[] args)

I don't understand why since I used the same function gave by microsoft.我不明白为什么因为我使用了微软提供的相同的 function。

Thanks for the replies感谢您的答复

I found out what was the problem.我发现了问题所在。

When you use the javascript function the stream you convert in Do.netStreamReference needs to be open.当您使用 javascript function 时,您在 Do.netStreamReference 中转换的 stream 需要打开。 Mine was closed by the return in the class where xml was generated.我的被 class 中的返回关闭,其中生成了 xml。

I just moved it out of the xml generation class to delete the return and put it in the same class as the javascript function and it worked.我只是将它从 883812976388 代 class 中移出以删除返回并将其放入与 javascript function 相同的 class 中并且它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM