helper.ts 1.4 KB

123456789101112131415161718192021222324252627282930
  1. function clickElement(element: HTMLElement): void {
  2. element.click();
  3. }
  4. function downloadFromUrl(options: { url: string, fileName?: string }): void {
  5. const anchorElement = document.createElement('a');
  6. anchorElement.href = options.url;
  7. anchorElement.download = options.fileName ?? '';
  8. anchorElement.click();
  9. anchorElement.remove();
  10. }
  11. function downloadFromByteArray(options: { byteArray: Uint8Array | string, fileName: string, contentType: string }): void {
  12. const url = typeof (options.byteArray) === 'string' ?
  13. // .NET 5 or earlier, the byte array in .NET is encoded to base64 string when it passes to JavaScript.
  14. // In that case, that base64 encoded string can be pass to the browser as a "data URL" directly.
  15. "data:" + options.contentType + ";base64," + options.byteArray :
  16. // .NET 6 or later, the byte array in .NET is passed to JavaScript as an UInt8Array efficiently.
  17. // - https://docs.microsoft.com/en-us/dotnet/core/compatibility/aspnet-core/6.0/byte-array-interop
  18. // In that case, the UInt8Array can be converted to an object URL and passed to the browser.
  19. // But don't forget to revoke the object URL when it is no longer needed.
  20. URL.createObjectURL(new Blob([options.byteArray], { type: options.contentType }))
  21. downloadFromUrl({ url: url, fileName: options.fileName });
  22. if (typeof (options.byteArray) !== 'string') URL.revokeObjectURL(url);
  23. }