简体   繁体   中英

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.

I used the method gave by Microsoft with the XDocument saved in a 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:

<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:

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.

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. Mine was closed by the return in the class where xml was generated.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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