aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Design proposal: #47685 Add blob() method to JS side of Blazor DotNetStreamReference

Open MaxxBahr opened this issue 1 year ago • 15 comments

Summary

Add a blob([mimeType: string]) method to DotNetStreamReference in Blazor, allowing developers to obtain a Blob from a .NET stream in JavaScript, without fully loading the stream into memory. We chose this specific issue, because it is a "good-first-issue" and we are participating in a germany wide competition, where the subject is to work on issues in open source projects. Link to issue: https://github.com/dotnet/aspnetcore/issues/47685

Motivation and goals

Blazor developers can currently pass .NET streams to JavaScript using DotNetStreamReference, which exposes two main methods:

  • stream() (returns a ReadableStream)
  • arrayBuffer() (loads the full stream into memory)

The problem:

  • There is no direct way to obtain a Blob, which is required for many web APIs (like <video> elements, file downloads or drag-and-drop functionality).
  • arrayBuffer() is not suitable for large files (like videos) because it fully buffers the stream in memory before use.
  • Using stream() gives a ReadableStream, but many APIs (like <video src=...>, URL.createObjectURL()) require a Blob, not a stream, and converting a ReadableStream into a Blob in JS is non-trivial and inefficient.

Adding a blob() method would:

  • Allow efficient handling of large files (like video or audio) without consuming excessive memory.
  • Simplify developer workflows by aligning with common web APIs that expect a Blob.
  • Close a usability gap in the current Blazor-JS interop system.

In scope

  • A new method blob([mimeType: string]) on DotNetStreamReference that returns a Blob representing the .NET stream.
  • Ensuring the Blob can be used with standard web APIs (e.g., <video>, <audio>, URL.createObjectURL()).
  • Keeping performance and memory usage efficient for large streams.

Out of scope

  • Changes to the existing stream() or arrayBuffer() methods.
  • Polyfills for browsers that lack Blob support (modern browsers are assumed).
  • Enhancements to streaming APIs beyond providing the Blob.

Risks / unknowns

  • Browser behavior: While Blobs are widely supported, the implementation detail of streaming data into a Blob without full buffering might depend on browser internals. Some browsers may still buffer the entire Blob in memory before making it available.

  • Memory use: Even if we avoid buffering in .NET or JS, the underlying browser may still end up consuming memory when the Blob is accessed, especially for very large files.

  • Implementation complexity: Creating a Blob from a .NET stream across JS interop might require platform-level work to ensure true streaming behavior rather than just buffering and converting.

Examples

Blazor usage example

<video @ref="videoPlayer" controls autoplay></video>

<button @onclick="PlayVideo">Play Streamed Video</button>

@code {
    private ElementReference videoPlayer;

    private async Task PlayVideo()
    {
        using var fileStream = File.OpenRead("bigvideo.mp4");
        var streamRef = new DotNetStreamReference(fileStream);

        // JS call to create a blob URL from the .NET stream
        var videoUrl = await JS.InvokeAsync<string>("createVideoBlobUrl", streamRef);

        // Set the video source
        await JS.InvokeVoidAsync("setVideoSrc", videoPlayer, videoUrl);
    }
}

JavaScript interop

window.createVideoBlobUrl = async function (streamRef) {
    const blob = await streamRef.blob("video/mp4");
    return URL.createObjectURL(blob);
};

window.setVideoSrc = function (videoElement, src) {
    videoElement.src = src;
};

MaxxBahr avatar May 07 '25 17:05 MaxxBahr

@MaxxBahr thanks for contacting us.

Memory use: Even if we avoid buffering in .NET or JS, the underlying browser may still end up consuming memory when the Blob is accessed, especially for very large files.

Blobs are immutable in JS, so if you have a stream you end up having to buffer all the data in memory.

Here is a sample snippet

async function readableStreamToBlob(readableStream, mimeType = "application/octet-stream") {
    const reader = readableStream.getReader();
    const chunks = [];

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        chunks.push(value); // Buffering chunks in memory
    }

    return new Blob(chunks, { type: mimeType });
}

// Example usage:
fetch('https://example.com/file') // Fetch returns a Response object with a ReadableStream
    .then(response => readableStreamToBlob(response.body, "application/pdf"))
    .then(blob => console.log(blob));

That's said, I think we will take in a PR if you want to send us one that contains the implementation and relevant tests.

javiercn avatar May 08 '25 11:05 javiercn

We would add a blob(type:string) method that would create a blob from the stream to suppor this scenario

javiercn avatar May 08 '25 11:05 javiercn

Is there a known way to unit test getBlob() given its reliance on browser-specific APIs like ReadableStream, Blob, and URL.createObjectURL? We weren’t able to find a viable approach within a Node.js test environment.

As a result, we’ve verified the method manually in real browsers using various input streams and confirmed that it behaves as expected. If an integration-style test (e.g., using Playwright) would be more suitable here, we’re happy to explore that as well.

MaxxBahr avatar Jun 05 '25 17:06 MaxxBahr

@javiercn We’ve opened a PR for this design proposal: #62298. If anything needs to be changed or improved, we’re happy to adjust accordingly.

TimoP01 avatar Jun 12 '25 16:06 TimoP01

“Hi, I’d like to work on this issue. Assigning it to myself if that’s okay. @lordoftech”

LordofTech avatar Jul 02 '25 12:07 LordofTech

“Hi, I’d like to work on this issue. Assigning it to myself if that’s okay. @lordoftech”

We already created a PR

MaxxBahr avatar Jul 02 '25 12:07 MaxxBahr

So i should leave it then

On Wed, 2 Jul 2025, 13:55 MaxxBahr, @.***> wrote:

MaxxBahr left a comment (dotnet/aspnetcore#61826) https://github.com/dotnet/aspnetcore/issues/61826#issuecomment-3027782970

“Hi, I’d like to work on this issue. Assigning it to myself if that’s okay. @LordofTech https://github.com/LordofTech”

We already created a PR

— Reply to this email directly, view it on GitHub https://github.com/dotnet/aspnetcore/issues/61826#issuecomment-3027782970, or unsubscribe https://github.com/notifications/unsubscribe-auth/BJKUXNEWMQ73MGHBZMONMLD3GPJE3AVCNFSM6AAAAAB4UO5ZIWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTAMRXG44DEOJXGA . You are receiving this because you were mentioned.Message ID: @.***>

LordofTech avatar Jul 02 '25 13:07 LordofTech

Hi! I’d like to work on this issue as my first contribution. Please assign it to me if it’s available.

soumo210340 avatar Jul 13 '25 13:07 soumo210340

No longer available.

On Sun, 13 Jul 2025, 14:33 Soumyadeep Chatterjee, @.***> wrote:

soumo210340 left a comment (dotnet/aspnetcore#61826) https://github.com/dotnet/aspnetcore/issues/61826#issuecomment-3067051630

Hi! I’d like to work on this issue as my first contribution. Please assign it to me if it’s available.

— Reply to this email directly, view it on GitHub https://github.com/dotnet/aspnetcore/issues/61826#issuecomment-3067051630, or unsubscribe https://github.com/notifications/unsubscribe-auth/BJKUXNFBSMTHCGBOXDSTJO33IJNZFAVCNFSM6AAAAAB4UO5ZIWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTANRXGA2TCNRTGA . You are receiving this because you were mentioned.Message ID: @.***>

LordofTech avatar Jul 13 '25 13:07 LordofTech

@javiercn there is not much traction here, may I take this issue?

ernest-koguc avatar Dec 07 '25 21:12 ernest-koguc

Yes pls do

On Sun, 7 Dec 2025, 22:09 ernest-koguc, @.***> wrote:

ernest-koguc left a comment (dotnet/aspnetcore#61826) https://github.com/dotnet/aspnetcore/issues/61826#issuecomment-3623392205

@javiercn https://github.com/javiercn there is not much traction here, may I take this issue?

— Reply to this email directly, view it on GitHub https://github.com/dotnet/aspnetcore/issues/61826#issuecomment-3623392205, or unsubscribe https://github.com/notifications/unsubscribe-auth/BJKUXNFNQYPCTXJYZG4FR234ASJQPAVCNFSM6AAAAAB4UO5ZIWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTMMRTGM4TEMRQGU . You are receiving this because you were mentioned.Message ID: @.***>

LordofTech avatar Dec 08 '25 09:12 LordofTech

Hi, this issue is still marked as open. May I work on it as my first issue? @javiercn @LordofTech

BryanAndy avatar Aug 05 '26 22:08 BryanAndy

Hi @javiercn @LordofTech , I'd like to work on this as my first ASP.NET Core contribution.

I saw the previous PRs linked to this issue (#62298, #66679, and #66921), so before getting too far into the implementation I'd like to confirm that a new PR is still welcome.

My current understanding of the approach is to add a blob(...) method to DotNetStreamReference that consumes the existing ReadableStream and constructs a Blob from its chunks. Based on your earlier comment, I understand that this won't make Blob creation truly streaming or eliminate buffering—the Blob ultimately needs the complete data—but it would provide a direct API and avoid requiring callers to first materialize the stream as an ArrayBuffer.

For tests, I'm planning to follow the existing JS interop test patterns and cover at least:

  • preservation of the stream's bytes across multiple chunks,
  • the supplied MIME type,
  • an empty stream,
  • and, if the existing unit-test environment can't exercise the required browser APIs, an appropriate browser/integration test following the repository's existing patterns.

One API detail I'd also like to confirm: should the intended signature require the MIME type (blob(type: string)), as mentioned above, or should it also support calling blob() without one?

Does this approach align with what you'd like, and is this issue still available for a new PR?

BryanAndy avatar Aug 25 '26 22:08 BryanAndy

Apps can create a Blob from a DotNetStreamReference with new Response(await streamRef.stream()).blob() and set its content type through the Response headers. We can keep this as an app-level pattern rather than add a dedicated blob() method.

kotlarmilos avatar Nov 20 '26 14:11 kotlarmilos