GithubHelp home page GithubHelp logo

kristofferstrube / blazor.fileapi Goto Github PK

View Code? Open in Web Editor NEW
27.0 1.0 2.0 10.01 MB

A Blazor wrapper for the browser File API.

Home Page: https://kristofferstrube.github.io/Blazor.FileAPI/

License: MIT License

C# 95.91% HTML 0.08% JavaScript 4.01%
api blazor blazor-interop blazor-webassembly blob csharp file file-api fileapi github-actions github-pages jsinterop url wrapper

blazor.fileapi's Introduction

License: MIT GitHub issues GitHub forks GitHub stars

NuGet Downloads (official NuGet)

Introduction

A Blazor wrapper for the browser File API

The API provides a standard for representing file objects in the browser and ways to select them and access their data. One of the most used interfaces that is at the core of this API is the Blob interface. This project implements a wrapper around the API for Blazor so that we can easily and safely interact with files in the browser.

Demo

The sample project can be demoed at https://kristofferstrube.github.io/Blazor.FileAPI/

On each page you can find the corresponding code for the example in the top right corner.

On the API Coverage Status page you can get an overview over what parts of the API we support currently.

Getting Started

Prerequisites

You need to install .NET 7.0 or newer to use the library.

Download .NET 7

Installation

You can install the package via NuGet with the Package Manager in your IDE or alternatively using the command line:

dotnet add package KristofferStrube.Blazor.FileAPI

Usage

The package can be used in Blazor WebAssembly and Blazor Server projects.

Import

You also need to reference the package in order to use it in your pages. This can be done in _Import.razor by adding the following.

@using KristofferStrube.Blazor.FileAPI

Creating wrapper instances

Most of this library is wrapper classes which can be instantiated from your code using the static Create and CreateAsync methods on the wrapper classes. An example could be to create an instance of a Blob that contains the text "Hello World!" and gets its Size and Type, read it as a ReadableStream, read as text directly, and slice it into a new Blob like this.

Blob blob = await Blob.CreateAsync(
    JSRuntime,
    blobParts: new BlobPart[] {
        "Hello ",
        new byte[] { 0X57, 0X6f, 0X72, 0X6c, 0X64, 0X21 }
    },
    options: new() { Type = "text/plain" }
);
ulong size = await blob.GetSizeAsync(); // 12
string type = await blob.GetTypeAsync(); // "text/plain"
ReadableStream stream = await blob.StreamAsync();
string text = await blob.TextAsync(); // "Hello World!"
Blob worldBlob = await blob.SliceAsync(6, 11); // Blob containing "World"

All creator methods take an IJSRuntime instance as the first parameter. The above sample will work in both Blazor Server and Blazor WebAssembly. If we only want to work with Blazor WebAssembly we can use the InProcess variant of the wrapper class. This is equivalent to the relationship between IJSRuntime and IJSInProcessRuntime. We can recreate the above sample using the BlobInProcess which will simplify some of the methods we can call on the Blob and how we access attributes.

BlobInProcess blob = await BlobInProcess.CreateAsync(
    JSRuntime,
    blobParts: new BlobPart[] {
        "Hello ",
        new byte[] { 0X57, 0X6f, 0X72, 0X6c, 0X64, 0X21 }
    },
    options: new() { Type = "text/plain" }
);
ulong size = blob.Size; // 12
string type = blob.Type; // "text/plain"
ReadableStreamInProcess stream = await blob.StreamAsync();
string text = await blob.TextAsync(); // "Hello World!"
BlobInProcess worldBlob = blob.Slice(6, 11); // BlobInProcess containing "World"

Some of the methods wrap a Promise so even in the InProcess variant we need to await it like we see for TextAsync above.

If you have an IJSObjectReference or an IJSInProcessObjectReference for a type equivalent to one of the classes wrapped in this package then you can construct a wrapper for it using another set of overloads of the static Create and CreateAsync methods on the appropriate class. In the below example we create wrapper instances from existing JS references to a File object.

// Blazor Server compatible.
IJSObjectReference jSFile; // JS Reference from other package or your own JSInterop.
File file = File.Create(JSRuntime, jSFile);

// InProcess only supported in Blazor WebAssembly.
IJSInProcessObjectReference jSFileInProcess; // JS Reference from other package or your own JSInterop.
FileInProcess fileInProcess = await File.CreateAsync(JSRuntime, jSFileInProcess);

Add to service collection

We have a single service in this package that wraps the URL interface. An easy way to make the service available in all your pages is by registering it in the IServiceCollection so that it can be dependency injected in the pages that need it. This is done in Program.cs by adding the following before you build the host and run it.

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// Other services are added.

builder.Services.AddURLService();

await builder.Build().RunAsync();

Inject in page

Then the service can be injected in a page and be used to create Blob URLs and revoke them like so:

@implements IAsyncDisposable
@inject IURLService URL;

<img src="@blobURL" alt="Some blob as image" />

@code {
    private string blobURL = "";

    protected override async Task OnInitializedAsync()
    {
        Blob blob; // We have some blob from somewhere.

        blobURL = await URL.CreateObjectURLAsync(blob);
    }

    public async ValueTask DisposeAsync()
    {
        await URL.RevokeObjectURLAsync(blobURL);
    }
}

You can likewise add the InProcess variant of the service (IURLServiceInProcess) using the AddURLServiceInProcess extension method which is only supported in Blazor WebAssembly projects.

Issues

Feel free to open issues on the repository if you find any errors with the package or have wishes for features.

Related repositories

This project uses the Blazor.Streams package to return a rich ReadableStream from the StreamAsync method on a Blob.

This project is used in the Blazor.FileSystem package to return a rich File object when getting the File from a FileSystemFileHandle and when writing a Blob to a FileSystemWritableFileSystem.

Related articles

This repository was build with inspiration and help from the following series of articles:

blazor.fileapi's People

Contributors

kristofferstrube avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

amcvoy jlchavez

blazor.fileapi's Issues

Customization of Javascript Location

As on other libraries the location of the javascript has impact on what is the latest version used and cached by the browser.

When using multiple Blazor WASM applications under different subfolders, from the one asp.net site the "base path" on the index.html file has a path like:

<base href="/inventory/">

As the original code has a fixed path: './_content/KristofferStrube.Blazor.FileAPI/KristofferStrube.Blazor.FileAPI.js', the "." (dot) on the path makes the browser look for the file in the current folder, but as the project is compiled all the referenced Razor Libraries are located under the root folder, and the browser won't locate it.

In cases when the applications are separated in different virtual folders those files would be duplicated on the various Blazor WASM applications and it would work, and may be usefull when different versions of the files are used based on the nuget's version. But currently on resource limits, IIS and it's ISAPI wrapper for .NET Core+, on a shared hosting it's limiting how many sites can be supportedm and I have 7 WASM apps.

There are different ways of solving this, but applications share functionality from different modules, it's an ERP, so it has multiple dependencies and pushing updates to one module, might and will impact on various Blazor WASM apps and REST APIs, may be complex CI/CD would help on pushing everything and switching App Service slots at once, so we consider it as a workaround for the current stage.

When fully launched I will move shared resources paths to a CDN so that all icons, fonts, css and other resources are fully shared by all the apps, to improve performance an reliability and storage costs. Your libraries reduce my complexity of handling a cache case on OPFS of certain user data that shouldn't change frequently but is required when any app loads, but my target is using a CDN for the static content, even if it's pulled in the background from another site, but allowing to granularly tweek caching of responses.

I've made none braking changes for this in the Pull Request #3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.