├── .EditorConfig ├── .github └── workflows │ └── main.yml ├── .gitignore ├── Blazor.FileAPI.sln ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── docs └── icon.png ├── samples └── KristofferStrube.Blazor.FileAPI.WasmExample │ ├── App.razor │ ├── KristofferStrube.Blazor.FileAPI.WasmExample.csproj │ ├── Pages │ ├── FileReaderSample.razor │ ├── Index.razor │ ├── Slice.razor │ ├── Status.razor │ └── StreamLargeBlob.razor │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Shared │ ├── MainLayout.razor │ ├── MainLayout.razor.css │ ├── NavMenu.razor │ └── NavMenu.razor.css │ ├── _Imports.razor │ └── wwwroot │ ├── 404.html │ ├── css │ ├── app.css │ ├── bootstrap │ │ ├── bootstrap.min.css │ │ └── bootstrap.min.css.map │ └── open-iconic │ │ ├── FONT-LICENSE │ │ ├── ICON-LICENSE │ │ ├── README.md │ │ └── font │ │ ├── css │ │ └── open-iconic-bootstrap.min.css │ │ └── fonts │ │ ├── open-iconic.eot │ │ ├── open-iconic.otf │ │ ├── open-iconic.svg │ │ ├── open-iconic.ttf │ │ └── open-iconic.woff │ ├── favicon.png │ ├── icon-192.png │ ├── images │ └── mountain.jpg │ └── index.html └── src └── KristofferStrube.Blazor.FileAPI ├── BaseJSWrapper.cs ├── Blob.InProcess.cs ├── Blob.cs ├── Converters ├── DateTimeConverter.cs └── EnumDescriptionConverter.cs ├── Enums └── EndingType.cs ├── Extensions ├── IJSRuntimeExtensions.cs └── IServiceCollectionExtensions.cs ├── File.InProcess.cs ├── File.cs ├── FileReader.InProcess.cs ├── FileReader.cs ├── IURLService.InProcess.cs ├── IURLService.cs ├── KristofferStrube.Blazor.FileAPI.csproj ├── Options ├── BlobPart.cs ├── BlobPropertyBag.cs └── FilePropertyBag.cs ├── ProgressEvent.InProcess.cs ├── ProgressEvent.cs ├── URLService.InProcess.cs ├── URLService.cs ├── _Imports.razor └── wwwroot └── KristofferStrube.Blazor.FileAPI.js /.EditorConfig: -------------------------------------------------------------------------------- 1 | [*] 2 | # All files 3 | dotnet_style_qualification_for_field = false 4 | dotnet_style_qualification_for_property = false 5 | dotnet_style_qualification_for_method = false 6 | dotnet_style_qualification_for_event = false 7 | dotnet_diagnostic.IDE0003.severity = warning 8 | dotnet_style_predefined_type_for_locals_parameters_members = true 9 | dotnet_style_predefined_type_for_member_access = true 10 | dotnet_diagnostic.IDE0049.severity = suggestion 11 | csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async 12 | dotnet_diagnostic.IDE0036.severity = error 13 | dotnet_style_require_accessibility_modifiers = always 14 | dotnet_diagnostic.IDE0040.severity = warning 15 | dotnet_style_readonly_field = true 16 | dotnet_diagnostic.IDE0044.severity = error 17 | csharp_prefer_static_local_function = true 18 | dotnet_diagnostic.IDE0062.severity = warning 19 | dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity 20 | dotnet_diagnostic.IDE0047.severity = warning 21 | dotnet_diagnostic.IDE0048.severity = warning 22 | dotnet_diagnostic.IDE0010.severity = error 23 | dotnet_style_object_initializer = true 24 | dotnet_diagnostic.IDE0017.severity = suggestion 25 | csharp_style_inlined_variable_declaration = true 26 | dotnet_diagnostic.IDE0018.severity = suggestion 27 | dotnet_style_collection_initializer = true 28 | dotnet_diagnostic.IDE0028.severity = warning 29 | dotnet_style_prefer_auto_properties = true 30 | dotnet_diagnostic.IDE0032.severity = suggestion 31 | dotnet_style_explicit_tuple_names = true 32 | dotnet_diagnostic.IDE0033.severity = warning 33 | csharp_prefer_simple_default_expression = false 34 | dotnet_diagnostic.IDE0034.severity = warning 35 | dotnet_style_prefer_inferred_tuple_names = true 36 | dotnet_style_prefer_inferred_anonymous_type_member_names = true 37 | dotnet_diagnostic.IDE0037.severity = suggestion 38 | csharp_style_prefer_local_over_anonymous_function = true 39 | dotnet_diagnostic.IDE0039.severity = warning 40 | csharp_style_deconstructed_variable_declaration = true 41 | dotnet_diagnostic.IDE0042.severity = suggestion 42 | dotnet_style_prefer_conditional_expression_over_assignment = true 43 | dotnet_diagnostic.IDE0045.severity = warning 44 | dotnet_style_prefer_conditional_expression_over_return = true 45 | dotnet_diagnostic.IDE0046.severity = warning 46 | dotnet_style_prefer_compound_assignment = true 47 | dotnet_diagnostic.IDE0054.severity = warning 48 | dotnet_diagnostic.IDE0074.severity = warning 49 | csharp_style_prefer_index_operator = true 50 | dotnet_diagnostic.IDE0056.severity = warning 51 | csharp_style_prefer_range_operator = true 52 | dotnet_diagnostic.IDE0057.severity = warning 53 | dotnet_diagnostic.IDE0070.severity = error 54 | dotnet_style_prefer_simplified_interpolation = true 55 | dotnet_diagnostic.IDE0071.severity = warning 56 | dotnet_diagnostic.IDE0072.severity = error 57 | dotnet_style_prefer_simplified_boolean_expressions = true 58 | dotnet_diagnostic.IDE0075.severity = warning 59 | dotnet_diagnostic.IDE0082.severity = error 60 | csharp_style_implicit_object_creation_when_type_is_apparent = true 61 | dotnet_diagnostic.IDE0090.severity = error 62 | dotnet_diagnostic.IDE0180.severity = warning 63 | csharp_style_namespace_declarations = file_scoped 64 | dotnet_diagnostic.IDE0160.severity = error 65 | dotnet_diagnostic.IDE0161.severity = error 66 | csharp_style_throw_expression = true 67 | dotnet_diagnostic.IDE0016.severity = warning 68 | dotnet_style_coalesce_expression = true 69 | dotnet_diagnostic.IDE0029.severity = warning 70 | dotnet_diagnostic.IDE0030.severity = warning 71 | dotnet_style_null_propagation = true 72 | dotnet_diagnostic.IDE0031.severity = warning 73 | dotnet_style_prefer_is_null_check_over_reference_equality_method = true 74 | dotnet_diagnostic.IDE0041.severity = warning 75 | csharp_style_prefer_null_check_over_type_check = true 76 | dotnet_diagnostic.IDE0150.severity = warning 77 | csharp_style_conditional_delegate_call = false 78 | dotnet_diagnostic.IDE1005.severity = warning 79 | csharp_style_var_for_built_in_types = false 80 | csharp_style_var_when_type_is_apparent = true 81 | csharp_style_var_elsewhere = false 82 | dotnet_diagnostic.IDE0007.severity = warning 83 | dotnet_diagnostic.IDE0008.severity = warning 84 | dotnet_diagnostic.IDE0001.severity = error 85 | dotnet_diagnostic.IDE0002.severity = error 86 | dotnet_diagnostic.IDE0004.severity = error 87 | dotnet_diagnostic.IDE0005.severity = error 88 | dotnet_diagnostic.IDE0035.severity = warning 89 | dotnet_diagnostic.IDE0051.severity = warning 90 | dotnet_diagnostic.IDE0052.severity = warning 91 | csharp_style_unused_value_expression_statement_preference = discard_variable 92 | dotnet_diagnostic.IDE0058.severity = warning 93 | csharp_style_unused_value_assignment_preference = discard_variable 94 | dotnet_diagnostic.IDE0059.severity = warning -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: 'Publish application' 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | paths-ignore: 8 | - '**/README.md' 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | # Checkout the code 15 | - uses: actions/checkout@v2 16 | 17 | # Install .NET 8.0 SDK 18 | - name: Setup .NET 8 preview 19 | uses: actions/setup-dotnet@v3 20 | with: 21 | dotnet-version: '8.0.x' 22 | include-prerelease: true 23 | 24 | # Generate the website 25 | - name: Publish 26 | run: dotnet publish samples/KristofferStrube.Blazor.FileAPI.WasmExample/KristofferStrube.Blazor.FileAPI.WasmExample.csproj --configuration Release --output build 27 | 28 | # Publish the website 29 | - name: GitHub Pages action 30 | if: ${{ github.ref == 'refs/heads/main' }} # Publish only when the push is on main 31 | uses: peaceiris/actions-gh-pages@v3.6.1 32 | with: 33 | github_token: ${{ secrets.PUBLISH_TOKEN }} 34 | publish_branch: gh-pages 35 | publish_dir: build/wwwroot 36 | allow_empty_commit: false 37 | keep_files: false 38 | force_orphan: true 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /Blazor.FileAPI.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristofferStrube.Blazor.FileAPI", "src\KristofferStrube.Blazor.FileAPI\KristofferStrube.Blazor.FileAPI.csproj", "{EE9E23DC-B900-4EA0-9F06-A190661AFE6D}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KristofferStrube.Blazor.FileAPI.WasmExample", "samples\KristofferStrube.Blazor.FileAPI.WasmExample\KristofferStrube.Blazor.FileAPI.WasmExample.csproj", "{65487B6C-BBC4-4D28-BA0A-4A0766B1099F}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {EE9E23DC-B900-4EA0-9F06-A190661AFE6D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {EE9E23DC-B900-4EA0-9F06-A190661AFE6D}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {EE9E23DC-B900-4EA0-9F06-A190661AFE6D}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {EE9E23DC-B900-4EA0-9F06-A190661AFE6D}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {65487B6C-BBC4-4D28-BA0A-4A0766B1099F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {65487B6C-BBC4-4D28-BA0A-4A0766B1099F}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {65487B6C-BBC4-4D28-BA0A-4A0766B1099F}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {65487B6C-BBC4-4D28-BA0A-4A0766B1099F}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {28DB186E-F7B5-4BED-BA05-1C4311AD56B1} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ## [0.4.0] - 2024-10-29 10 | ### Deprecated 11 | - Deprecated synchronous `Blob.Create` and `File.Create` creator methods in favor of asynchronous `CreateAsync` methods. 12 | - Deprecated `FileReader` event members `OnLoadStart`, `OnProgress`, `OnLoad`, `OnAbort`, and `OnLoadEnd` in favor of methods for adding and removing event listeners like `AddOnLoadEventListenerAsync` and `RemoveOnLoadEventListenerAsync`. 13 | - Deprecated `FileReaderInProcess` event members `OnLoadStart`, `OnProgress`, `OnLoad`, `OnAbort`, and `OnLoadEnd` in favor of methods for adding and removing event listeners like `AddOnLoadEventListener` and `RemoveOnLoadEventListener`. 14 | ### Changed 15 | - Changed the version of Blazor.Streams to use the newest version which is 0.5.0. 16 | - `FileReader` now extends `EventTarget` to expose all methods for adding/removing event listeners and dispatching events. 17 | - `FileReaderInProcess` now implements `IEventTargetInProcess` to expose all methods for adding/removing event listeners and dispatching events. 18 | - `ProgressEvent` now extends `Event` to expose methods for getting general information about the event like the target, type, and time stamp and asynchronous methods for stopping propagation and preventing default behavior programmatically. 19 | - `ProgressEventInProcess` now exposes same members as `EventInProcess`. This includes properties for getting general information about the event like the target, type, and time stamp and synchronous methods for stopping propagation and preventing default behavior programmatically. 20 | ### Added 21 | - Added target for .NET 8. 22 | - Added `CreateAsync` creator methods for all wrapper classes. 23 | - Added `IAsyncDisposable` implementation to all wrapper classes that ensures that their helpers and `JSReference`s are disposed. 24 | 25 | ## [0.3.0] - 2023-03-16 26 | ### Changed 27 | - Changed .NET version to `7.0`. 28 | - Changed the version of Blazor.Streams to use the newest version which is `0.3.0`. 29 | ### Added 30 | - Added the generation of a documentation file packaging all XML comments with the package. 31 | 32 | ## [0.2.0] - 2022-11-18 33 | ### Added 34 | - Added implicit converters for `BlobPart` from `Blob`, `byte[]`, and `string`. 35 | ### Fixed 36 | - Fixed that the saturating creator for `FileReader` didn't register event handlers. 37 | 38 | ## [0.1.1] - 2022-11-10 39 | ### Fixed 40 | - `Blob`'s method `ArrayBufferAsync` used an `IJSInProcessObjectReference` which is not supported in Blazor Server. This was changed to use `IJSObjectReference`. 41 | ### Changed 42 | - Changed the version of Blazor.Streams to use the newest version which is `0.2.2`. 43 | 44 | ## [0.1.0] - 2022-11-08 45 | ### Added 46 | - Made the initial implementation that covers most of the API. -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | Contributing includes many different actions. It is not only writing code. Contributions like discussing solutions in open issues are easily as valuable as contributing code as we can then find the best solution with the perspective of multiple people. 3 | 4 | ## Bugs and feature requests 5 | If you find any bugs in the project or have requests for features, then please [Open a new Issue](https://github.com/KristofferStrube/Blazor.FileAPI/issues/new). 6 | 7 | ## Contributing Code and Samples 8 | Before you contribute to the project, you will need to get confirmation from the library author that the contribution is welcome. 9 | This can help align the scope of the contribution so that you and the author agree on the solution and how you ensure the change is maintainable with the existing users in mind. 10 | Once you are ready to start coding try to follow these code guidelines: 11 | - Make a fork of the current `main` branch. 12 | - Follow the existing coding conventions used in the project. This includes tab style, naming conventions, etc. 13 | - If your contribution is a new feature, try to add a demo that demonstrates how this will be used in the sample project. 14 | - Any code or sample you share as a part of the resulting Pull Request should fall under the MIT license agreement. 15 | - You don't need to update the version number of the project as the maintainer will do this when making the next release after the Pull Request has been merged. 16 | - Keep your Pull Request to the point. I.e., if your Pull Request is related to fixing a bug then try not to touch any other files than the ones related to that issue as this will make the chance of the PR being merged without change requests more likely. 17 | 18 | ## Submitting a Pull Request 19 | If you don't know what a pull request is, read this article: https://help.github.com/articles/using-pull-requests. Make sure the repository can be built and that the related sample project still works as intended. It is also a good idea to familiarize yourself with the project workflow and our coding conventions. 20 | 21 | ## Ensuring that your contribution will be accepted 22 | You might also read these two blog posts on contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza and [Don't "Push" Your Pull Requests](https://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik. These blog posts highlight good open-source collaboration etiquette and help align expectations between you and us. 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Kristoffer Strube 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](/LICENSE.md) 2 | [![GitHub issues](https://img.shields.io/github/issues/KristofferStrube/Blazor.FileAPI)](https://github.com/KristofferStrube/Blazor.FileAPI/issues) 3 | [![GitHub forks](https://img.shields.io/github/forks/KristofferStrube/Blazor.FileAPI)](https://github.com/KristofferStrube/Blazor.FileAPI/network/members) 4 | [![GitHub stars](https://img.shields.io/github/stars/KristofferStrube/Blazor.FileAPI)](https://github.com/KristofferStrube/Blazor.FileAPI/stargazers) 5 | 6 | [![NuGet Downloads (official NuGet)](https://img.shields.io/nuget/dt/KristofferStrube.Blazor.FileAPI?label=NuGet%20Downloads)](https://www.nuget.org/packages/KristofferStrube.Blazor.FileAPI/) 7 | 8 | # Introduction 9 | A Blazor wrapper for the browser [File API](https://www.w3.org/TR/FileAPI/) 10 | 11 | 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](https://www.w3.org/TR/FileAPI/#dfn-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. 12 | 13 | # Demo 14 | The sample project can be demoed at https://kristofferstrube.github.io/Blazor.FileAPI/ 15 | 16 | On each page you can find the corresponding code for the example in the top right corner. 17 | 18 | On the *API Coverage Status* page you can get an overview over what parts of the API we support currently. 19 | 20 | # Getting Started 21 | ## Prerequisites 22 | You need to install .NET 7.0 or newer to use the library. 23 | 24 | [Download .NET 7](https://dotnet.microsoft.com/download/dotnet/7.0) 25 | 26 | ## Installation 27 | You can install the package via NuGet with the Package Manager in your IDE or alternatively using the command line: 28 | ```bash 29 | dotnet add package KristofferStrube.Blazor.FileAPI 30 | ``` 31 | 32 | # Usage 33 | The package can be used in Blazor WebAssembly and Blazor Server projects. 34 | ## Import 35 | 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. 36 | ```razor 37 | @using KristofferStrube.Blazor.FileAPI 38 | ``` 39 | 40 | ## Creating wrapper instances 41 | 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. 42 | 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. 43 | ```csharp 44 | await using Blob blob = await Blob.CreateAsync( 45 | JSRuntime, 46 | blobParts: new BlobPart[] { 47 | "Hello ", 48 | new byte[] { 0X57, 0X6f, 0X72, 0X6c, 0X64, 0X21 } 49 | }, 50 | options: new() { Type = "text/plain" } 51 | ); 52 | ulong size = await blob.GetSizeAsync(); // 12 53 | string type = await blob.GetTypeAsync(); // "text/plain" 54 | await using ReadableStream stream = await blob.StreamAsync(); 55 | string text = await blob.TextAsync(); // "Hello World!" 56 | await using Blob worldBlob = await blob.SliceAsync(6, 11); // Blob containing "World" 57 | ``` 58 | 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. 59 | ```csharp 60 | await using BlobInProcess blob = await BlobInProcess.CreateAsync( 61 | JSRuntime, 62 | blobParts: new BlobPart[] { 63 | "Hello ", 64 | new byte[] { 0X57, 0X6f, 0X72, 0X6c, 0X64, 0X21 } 65 | }, 66 | options: new() { Type = "text/plain" } 67 | ); 68 | ulong size = blob.Size; // 12 69 | string type = blob.Type; // "text/plain" 70 | await using ReadableStreamInProcess stream = await blob.StreamAsync(); 71 | string text = await blob.TextAsync(); // "Hello World!" 72 | await using BlobInProcess worldBlob = blob.Slice(6, 11); // BlobInProcess containing "World" 73 | ``` 74 | Some of the methods wrap a `Promise` so even in the `InProcess` variant we need to await it like we see for `TextAsync` above. 75 | 76 | 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. 77 | ```csharp 78 | // Blazor Server compatible. 79 | IJSObjectReference jSFile; // JS Reference from other package or your own JSInterop. 80 | await using File file = File.CreateAsync(JSRuntime, jSFile, new() { DisposesJSReference = true }); 81 | 82 | // InProcess only supported in Blazor WebAssembly. 83 | IJSInProcessObjectReference jSFileInProcess; // JS Reference from other package or your own JSInterop. 84 | await using FileInProcess fileInProcess = await File.CreateAsync(JSRuntime, jSFileInProcess); 85 | ``` 86 | 87 | ## Add to service collection 88 | 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. 89 | ```csharp 90 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 91 | builder.RootComponents.Add("#app"); 92 | builder.RootComponents.Add("head::after"); 93 | 94 | // Other services are added. 95 | 96 | builder.Services.AddURLService(); 97 | 98 | await builder.Build().RunAsync(); 99 | ``` 100 | ## Inject in page 101 | Then the service can be injected in a page and be used to create Blob URLs and revoke them like so: 102 | ```razor 103 | @implements IAsyncDisposable 104 | @inject IURLService URL; 105 | 106 | Some blob as image 107 | 108 | @code { 109 | private string blobURL = ""; 110 | 111 | protected override async Task OnInitializedAsync() 112 | { 113 | Blob blob; // We have some blob from somewhere. 114 | 115 | blobURL = await URL.CreateObjectURLAsync(blob); 116 | } 117 | 118 | public async ValueTask DisposeAsync() 119 | { 120 | await URL.RevokeObjectURLAsync(blobURL); 121 | } 122 | } 123 | ``` 124 | You can likewise add the `InProcess` variant of the service (`IURLServiceInProcess`) using the `AddURLServiceInProcess` extension method which is only supported in Blazor WebAssembly projects. 125 | 126 | # Issues 127 | Feel free to open issues on the repository if you find any errors with the package or have wishes for features. 128 | 129 | # Related repositories 130 | The library uses the following other packages to support its features: 131 | - https://github.com/KristofferStrube/Blazor.Streams (To return a rich `ReadableStream` from the `StreamAsync` method on a `Blob`) 132 | - https://github.com/KristofferStrube/Blazor.DOM (To implement `FileReader` which extends `EventTarget` and to implement `ProgressEvent` which extends `Event`) 133 | 134 | The library is used in the following other packages to support their features: 135 | - https://github.com/KristofferStrube/Blazor.FileSystem (to return a rich `File` object when getting the `File` from a `FileSystemFileHandle` and when writing a `Blob` to a `FileSystemWritableFileSystem`) 136 | - https://github.com/KristofferStrube/Blazor.MediaStreamRecording (to get the data from a `BlobEvent` which is created when a chunk of a stream has been recorded) 137 | 138 | # Related articles 139 | This repository was build with inspiration and help from the following series of articles: 140 | 141 | - [Wrapping JavaScript libraries in Blazor WebAssembly/WASM](https://blog.elmah.io/wrapping-javascript-libraries-in-blazor-webassembly-wasm/) 142 | - [Call anonymous C# functions from JS in Blazor WASM](https://blog.elmah.io/call-anonymous-c-functions-from-js-in-blazor-wasm/) 143 | - [Using JS Object References in Blazor WASM to wrap JS libraries](https://blog.elmah.io/using-js-object-references-in-blazor-wasm-to-wrap-js-libraries/) 144 | - [Blazor WASM 404 error and fix for GitHub Pages](https://blog.elmah.io/blazor-wasm-404-error-and-fix-for-github-pages/) 145 | - [How to fix Blazor WASM base path problems](https://blog.elmah.io/how-to-fix-blazor-wasm-base-path-problems/) 146 | -------------------------------------------------------------------------------- /docs/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/docs/icon.png -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/App.razor: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | Not found 8 | 9 |

Sorry, there's nothing at this address.

10 |
11 |
12 |
13 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/KristofferStrube.Blazor.FileAPI.WasmExample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Pages/FileReaderSample.razor: -------------------------------------------------------------------------------- 1 | @page "/FileReaderSample" 2 | @using System.Text 3 | @implements IAsyncDisposable 4 | 5 | @inject IJSRuntime JSRuntime 6 | @inject HttpClient HttpClient 7 | 8 | FileAPI - FileReader 9 | 10 |

Using the FileReader to load an image in different ways.

11 | In this sample we download an image using the HttpClient and create a new Blob from that. 12 | We then use the methods of the FileReader interface to read the Blob in different ways and convert those different results to an image. 13 |
14 |
15 | 16 | 17 | 18 | 19 | 20 |
21 | 23 |
24 | 25 | 26 | @code { 27 | string log = ""; 28 | private string imageUrl = ""; 29 | private Blob? blob; 30 | 31 | protected override async Task OnInitializedAsync() 32 | { 33 | var imageBytes = await HttpClient.GetByteArrayAsync($"images/mountain.jpg"); 34 | blob = await Blob.CreateAsync( 35 | JSRuntime, 36 | blobParts: new BlobPart[] { imageBytes }, 37 | options: new() { Type = "image/png" } 38 | ); 39 | } 40 | 41 | private void GetProgress(ProgressEventInProcess eventArgs) 42 | { 43 | var time = eventArgs.TimeStamp; 44 | var progress = eventArgs.LengthComputable ? $"({eventArgs.Loaded}/{eventArgs.Total})" : ""; 45 | log += $"{time:F2} - {eventArgs.Type}: {progress}\n"; 46 | StateHasChanged(); 47 | } 48 | 49 | private async Task GetProgressAsync(ProgressEvent eventArgs) 50 | { 51 | var time = await eventArgs.GetTimeStampAsync(); 52 | var type = await eventArgs.GetTypeAsync(); 53 | var progress = await eventArgs.GetLengthComputableAsync() ? $"({await eventArgs.GetLoadedAsync()}/{await eventArgs.GetTotalAsync()})" : ""; 54 | log += $"{time:F2} - {type}: {progress}\n"; 55 | StateHasChanged(); 56 | } 57 | 58 | public async Task ReadAsArrayBufferAsync() 59 | { 60 | log = ""; 61 | await using var fileReader = await FileReader.CreateAsync(JSRuntime); 62 | 63 | await using var eventListener = await EventListener.CreateAsync(JSRuntime, GetProgressAsync); 64 | await using var loadEndEventLister = await EventListener.CreateAsync(JSRuntime, async e => 65 | { 66 | imageUrl = "data:image/png;base64," + Convert.ToBase64String(await fileReader.GetResultAsByteArrayAsync() ?? new byte[0]); 67 | await GetProgressAsync(e); 68 | }); 69 | 70 | await fileReader.AddOnLoadStartEventListenerAsync(eventListener); 71 | await fileReader.AddOnProgressEventListenerAsync(eventListener); 72 | await fileReader.AddOnLoadEventListenerAsync(eventListener); 73 | await fileReader.AddOnAbortEventListenerAsync(eventListener); 74 | await fileReader.AddOnErrorEventListenerAsync(eventListener); 75 | await fileReader.AddOnLoadEndEventListenerAsync(loadEndEventLister); 76 | 77 | await fileReader.ReadAsArrayBufferAsync(blob!); 78 | } 79 | 80 | public async Task ReadAsArrayBufferInProcessAsync() 81 | { 82 | log = ""; 83 | await using var fileReader = await FileReaderInProcess.CreateAsync(JSRuntime); 84 | 85 | await using var eventListener = await EventListenerInProcess.CreateAsync(JSRuntime, e => 86 | { 87 | if (e.Type == "loadend") 88 | { 89 | imageUrl = "data:image/png;base64," + Convert.ToBase64String(fileReader.ResultAsByteArray ?? new byte[0]); 90 | } 91 | GetProgress(e); 92 | }); 93 | 94 | fileReader.AddOnLoadStartEventListener(eventListener); 95 | fileReader.AddOnProgressEventListener(eventListener); 96 | fileReader.AddOnLoadEventListener(eventListener); 97 | fileReader.AddOnAbortEventListener(eventListener); 98 | fileReader.AddOnErrorEventListener(eventListener); 99 | fileReader.AddOnLoadEndEventListener(eventListener); 100 | 101 | fileReader.ReadAsArrayBuffer(blob!); 102 | } 103 | 104 | public async Task ReadAsBinaryStringAsync() 105 | { 106 | log = ""; 107 | await using var fileReader = await FileReader.CreateAsync(JSRuntime); 108 | 109 | await using var eventListener = await EventListener.CreateAsync(JSRuntime, GetProgressAsync); 110 | await using var loadEndEventLister = await EventListener.CreateAsync(JSRuntime, async e => 111 | { 112 | var bytes = (await fileReader.GetResultAsStringAsync() ?? "").Select(c => (byte)c).ToArray(); 113 | imageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes); 114 | await GetProgressAsync(e); 115 | }); 116 | 117 | await fileReader.AddOnLoadStartEventListenerAsync(eventListener); 118 | await fileReader.AddOnProgressEventListenerAsync(eventListener); 119 | await fileReader.AddOnLoadEventListenerAsync(eventListener); 120 | await fileReader.AddOnAbortEventListenerAsync(eventListener); 121 | await fileReader.AddOnErrorEventListenerAsync(eventListener); 122 | await fileReader.AddOnLoadEndEventListenerAsync(loadEndEventLister); 123 | 124 | await fileReader.ReadAsBinaryStringAsync(blob!); 125 | } 126 | 127 | public void ReadAsText() 128 | { 129 | log = "We can't read an image as text. ;)"; 130 | imageUrl = ""; 131 | StateHasChanged(); 132 | } 133 | 134 | public async Task ReadAsDataURLAsync() 135 | { 136 | log = ""; 137 | await using var fileReader = await FileReader.CreateAsync(JSRuntime); 138 | 139 | await using var eventListener = await EventListener.CreateAsync(JSRuntime, GetProgressAsync); 140 | await using var loadEndEventLister = await EventListener.CreateAsync(JSRuntime, async e => 141 | { 142 | imageUrl = await fileReader.GetResultAsStringAsync() ?? ""; 143 | await GetProgressAsync(e); 144 | }); 145 | 146 | await fileReader.AddOnLoadStartEventListenerAsync(eventListener); 147 | await fileReader.AddOnProgressEventListenerAsync(eventListener); 148 | await fileReader.AddOnLoadEventListenerAsync(eventListener); 149 | await fileReader.AddOnAbortEventListenerAsync(eventListener); 150 | await fileReader.AddOnErrorEventListenerAsync(eventListener); 151 | await fileReader.AddOnLoadEndEventListenerAsync(loadEndEventLister); 152 | 153 | await fileReader.ReadAsDataURLAsync(blob!); 154 | } 155 | 156 | public async ValueTask DisposeAsync() 157 | { 158 | if (blob is not null) 159 | { 160 | await blob.DisposeAsync(); 161 | } 162 | } 163 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Pages/Index.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | @implements IAsyncDisposable 3 | 4 | @inject IJSRuntime JSRuntime 5 | @inject HttpClient HttpClient 6 | @inject IURLServiceInProcess URL 7 | 8 | FileAPI - Index 9 | 10 |

Loading an image as a Blob

11 | In this sample we download an image using the HttpClient and create a new File from that. 12 | Using the methods from the URL interface we construct a Blob URL for the image and use that as the source for the img-tag below. 13 |
14 | 15 |
16 | file name: @file?.Name 17 |
18 | last modified: @file?.LastModified 19 |
20 | content type: @file?.Type 21 | 22 | 23 | @code { 24 | private string blobURL = ""; 25 | private FileInProcess? file; 26 | 27 | protected override async Task OnInitializedAsync() 28 | { 29 | var imageName = "mountain.jpg"; 30 | 31 | var imageBytes = await HttpClient.GetByteArrayAsync($"images/{imageName}"); 32 | file = await FileInProcess.CreateAsync( 33 | JSRuntime, 34 | fileBits: new BlobPart[] { imageBytes }, 35 | fileName: imageName, 36 | options: new() { Type = "image/png", LastModified = DateTime.Now } 37 | ); 38 | blobURL = URL.CreateObjectURL(file); 39 | } 40 | 41 | public async ValueTask DisposeAsync() 42 | { 43 | if (file is not null) 44 | { 45 | await file.DisposeAsync(); 46 | } 47 | if (blobURL is not "") 48 | { 49 | URL.RevokeObjectURL(blobURL); 50 | } 51 | } 52 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Pages/Slice.razor: -------------------------------------------------------------------------------- 1 | @page "/Slice" 2 | @inject IJSRuntime JSRuntime 3 | 4 | FileAPI - Slice 5 | 6 |

Slicing a Blob

7 | Here we can see how we can slice a Blob. We construct a Blob with the numbers from 0 to 49 encoded as bytes. 8 |
9 |
10 | Slice(20, 30): @slice20_30 11 |
12 |
13 | SliceAsync(end: 10): @slice_end_10 14 |
15 |
16 | SliceAsync(start: 40): @slice_start_40 17 |
18 |
19 | SliceAsync(10, 20, "text/csv"): @slice10_20 with content type @slice10_20ContentType 20 |
21 | 22 | @code { 23 | string slice20_30 = ""; 24 | string slice_end_10 = ""; 25 | string slice_start_40 = ""; 26 | string slice10_20 = ""; 27 | string slice10_20ContentType = ""; 28 | 29 | protected override async Task OnInitializedAsync() 30 | { 31 | await using var blob = await BlobInProcess.CreateAsync( 32 | JSRuntime, 33 | blobParts: new BlobPart[] { Enumerable.Range(0, 50).Select(i => (byte)i).ToArray() }, 34 | options: new() { Type = "text/plain" } 35 | ); 36 | 37 | slice20_30 = string.Join(",", (await (blob.Slice(20, 30)).ArrayBufferAsync()).Select(b => b.ToString())); 38 | slice_end_10 = string.Join(",", (await (await blob.SliceAsync(end: 10)).ArrayBufferAsync()).Select(b => b.ToString())); 39 | slice_start_40 = string.Join(",", (await (await blob.SliceAsync(start: 40)).ArrayBufferAsync()).Select(b => b.ToString())); 40 | 41 | var slice = await blob.SliceAsync(10, 20, "text/csv"); 42 | slice10_20 = string.Join(",", (await slice.ArrayBufferAsync()).Select(b => b.ToString())); 43 | slice10_20ContentType = await slice.GetTypeAsync(); 44 | } 45 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Pages/Status.razor: -------------------------------------------------------------------------------- 1 | @page "/Status" 2 | 3 | @inject IJSRuntime JSRuntime 4 | 5 | FileAPI - Status 6 | 7 |
@((MarkupString)compareText)
8 | 9 | @code { 10 | private string compareText = ""; 11 | 12 | protected override void OnInitialized() 13 | { 14 | var compareLines = new List(); 15 | var lines = webIDL.Replace("<", "<").Split('\n'); 16 | for (int i = 0; i < lines.Count(); i++) 17 | { 18 | var color = supportedRows.Any(interval => i >= interval.start && i <= interval.end) ? "lightgreen" : "pink"; 19 | compareLines.Add($"""{lines[i]}"""); 20 | } 21 | 22 | compareText = string.Join("", compareLines); 23 | StateHasChanged(); 24 | } 25 | 26 | private (int start, int end)[] supportedRows = new (int start, int end)[] { (0, 39), (47, 77), (90, 94) }; 27 | 28 | private const string webIDL = @"[Exposed=(Window,Worker), Serializable] 29 | interface Blob { 30 | constructor(optional sequence blobParts, 31 | optional BlobPropertyBag options = {}); 32 | 33 | readonly attribute unsigned long long size; 34 | readonly attribute DOMString type; 35 | 36 | // slice Blob into byte-ranged chunks 37 | Blob slice(optional [Clamp] long long start, 38 | optional [Clamp] long long end, 39 | optional DOMString contentType); 40 | 41 | // read from the Blob. 42 | [NewObject] ReadableStream stream(); 43 | [NewObject] Promise text(); 44 | [NewObject] Promise arrayBuffer(); 45 | }; 46 | 47 | enum EndingType { ""transparent"", ""native"" }; 48 | 49 | dictionary BlobPropertyBag { 50 | DOMString type = """"; 51 | EndingType endings = ""transparent""; 52 | }; 53 | 54 | typedef (BufferSource or Blob or USVString) BlobPart; 55 | 56 | [Exposed=(Window,Worker), Serializable] 57 | interface File : Blob { 58 | constructor(sequence fileBits, 59 | USVString fileName, 60 | optional FilePropertyBag options = {}); 61 | readonly attribute DOMString name; 62 | readonly attribute long long lastModified; 63 | }; 64 | 65 | dictionary FilePropertyBag : BlobPropertyBag { 66 | long long lastModified; 67 | }; 68 | 69 | [Exposed=(Window,Worker), Serializable] 70 | interface FileList { 71 | getter File? item(unsigned long index); 72 | readonly attribute unsigned long length; 73 | }; 74 | 75 | [Exposed=(Window,Worker)] 76 | interface FileReader: EventTarget { 77 | constructor(); 78 | // async read methods 79 | undefined readAsArrayBuffer(Blob blob); 80 | undefined readAsBinaryString(Blob blob); 81 | undefined readAsText(Blob blob, optional DOMString encoding); 82 | undefined readAsDataURL(Blob blob); 83 | 84 | undefined abort(); 85 | 86 | // states 87 | const unsigned short EMPTY = 0; 88 | const unsigned short LOADING = 1; 89 | const unsigned short DONE = 2; 90 | 91 | readonly attribute unsigned short readyState; 92 | 93 | // File or Blob data 94 | readonly attribute (DOMString or ArrayBuffer)? result; 95 | 96 | readonly attribute DOMException? error; 97 | 98 | // event handler content attributes 99 | attribute EventHandler onloadstart; 100 | attribute EventHandler onprogress; 101 | attribute EventHandler onload; 102 | attribute EventHandler onabort; 103 | attribute EventHandler onerror; 104 | attribute EventHandler onloadend; 105 | }; 106 | 107 | [Exposed=(DedicatedWorker,SharedWorker)] 108 | interface FileReaderSync { 109 | constructor(); 110 | // Synchronously return strings 111 | 112 | ArrayBuffer readAsArrayBuffer(Blob blob); 113 | DOMString readAsBinaryString(Blob blob); 114 | DOMString readAsText(Blob blob, optional DOMString encoding); 115 | DOMString readAsDataURL(Blob blob); 116 | }; 117 | 118 | [Exposed=(Window,DedicatedWorker,SharedWorker)] 119 | partial interface URL { 120 | static DOMString createObjectURL((Blob or MediaSource) obj); 121 | static undefined revokeObjectURL(DOMString url); 122 | };"; 123 | 124 | } 125 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Pages/StreamLargeBlob.razor: -------------------------------------------------------------------------------- 1 | @page "/StreamLargeBlob" 2 | @inject IJSRuntime JSRuntime 3 | 4 | FileAPI - Stream Large Blob 5 | 6 |

Streaming a large Blob

7 | A common problem that people face when working with files is that they can be very big. 8 | This is especially a problem if you want to read them in Blazor Server where there is a limit on the size of messages that can be sent over SignalR. 9 |
10 | This sample will illustrate stream reading a large Blob to .NET using the inbuilt stream() method available on a Blob. 11 |
12 |
13 |
    14 |
  1. We have created a method in JS called hugeBlob() which creates a huge object in the form of a large empty array, serialized to a JSON string, and then parsed into the Blob constructor.
  2. 15 |
  3. We construct a wrapper around the JS object reference (jSBlob) by calling Blob.CreateAsync(JSRuntime, jSBlob).
  4. 16 |
  5. We get a ReadableStream from the Blob by calling await blob.StreamAsync().
  6. 17 |
  7. We get the default reader of the stream by calling await stream.GetDefaultReaderAsync().
  8. 18 |
  9. We iterate the chunks of the reader and append the chunk to our result. Below you can see chunk sizes read and the length of the result that has been built.
  10. 19 |
20 | 21 | Last Read Lengths: @string.Join(", ", readLengths) 22 |
23 | Accumulatively Result Length: @result.Length characters 24 | 25 | @code { 26 | private string result = ""; 27 | private List readLengths = new(); 28 | 29 | protected override async Task OnAfterRenderAsync(bool firstRender) 30 | { 31 | if (!firstRender) return; 32 | 33 | var jSBlob = await JSRuntime.InvokeAsync("hugeBlob"); 34 | 35 | await using var blob = await Blob.CreateAsync(JSRuntime, jSBlob); 36 | 37 | await using var stream = await blob.StreamAsync(); 38 | 39 | await using var reader = await stream.GetDefaultReaderAsync(); 40 | 41 | await foreach (var chunk in reader.IterateStringsAsync()) 42 | { 43 | if (chunk is null) break; 44 | readLengths.Add(chunk.Length); 45 | result += chunk; 46 | StateHasChanged(); 47 | await Task.Delay(100); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Program.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.FileAPI; 2 | using KristofferStrube.Blazor.FileAPI.WasmExample; 3 | using Microsoft.AspNetCore.Components.Web; 4 | using Microsoft.AspNetCore.Components.WebAssembly.Hosting; 5 | 6 | var builder = WebAssemblyHostBuilder.CreateDefault(args); 7 | builder.RootComponents.Add("#app"); 8 | builder.RootComponents.Add("head::after"); 9 | 10 | builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); 11 | builder.Services.AddURLServiceInProcess(); 12 | 13 | await builder.Build().RunAsync(); 14 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:62525", 7 | "sslPort": 44304 8 | } 9 | }, 10 | "profiles": { 11 | "http": { 12 | "commandName": "Project", 13 | "dotnetRunMessages": true, 14 | "launchBrowser": true, 15 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 16 | "applicationUrl": "http://localhost:5030", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 26 | "applicationUrl": "https://localhost:7064;http://localhost:5030", 27 | "environmentVariables": { 28 | "ASPNETCORE_ENVIRONMENT": "Development" 29 | } 30 | }, 31 | "IIS Express": { 32 | "commandName": "IISExpress", 33 | "launchBrowser": true, 34 | "inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}", 35 | "environmentVariables": { 36 | "ASPNETCORE_ENVIRONMENT": "Development" 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Shared/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | @inject NavigationManager NavigationManager 3 | 4 |
5 | 8 | 9 |
10 |
11 | 12 | 13 | 14 |
15 | 16 |
17 | @Body 18 |
19 |
20 |
21 | 22 | @code { 23 | private string relativeUri => NavigationManager.ToBaseRelativePath(NavigationManager.Uri); 24 | 25 | protected string page => (string.IsNullOrEmpty(relativeUri) ? "Index" : relativeUri) + ".razor"; 26 | } -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Shared/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | .page { 2 | position: relative; 3 | display: flex; 4 | flex-direction: column; 5 | } 6 | 7 | main { 8 | flex: 1; 9 | } 10 | 11 | .sidebar { 12 | background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%); 13 | } 14 | 15 | .top-row { 16 | background-color: #f7f7f7; 17 | border-bottom: 1px solid #d6d5d5; 18 | justify-content: flex-end; 19 | height: 3.5rem; 20 | display: flex; 21 | align-items: center; 22 | } 23 | 24 | .top-row ::deep a, .top-row ::deep .btn-link { 25 | white-space: nowrap; 26 | margin-left: 1.5rem; 27 | text-decoration: none; 28 | } 29 | 30 | .top-row ::deep a:hover, .top-row ::deep .btn-link:hover { 31 | text-decoration: underline; 32 | } 33 | 34 | .top-row ::deep a:first-child { 35 | overflow: hidden; 36 | text-overflow: ellipsis; 37 | } 38 | 39 | @media (max-width: 640.98px) { 40 | .top-row:not(.auth) { 41 | display: none; 42 | } 43 | 44 | .top-row.auth { 45 | justify-content: space-between; 46 | } 47 | 48 | .top-row ::deep a, .top-row ::deep .btn-link { 49 | margin-left: 0; 50 | } 51 | } 52 | 53 | @media (min-width: 641px) { 54 | .page { 55 | flex-direction: row; 56 | } 57 | 58 | .sidebar { 59 | width: 250px; 60 | height: 100vh; 61 | position: sticky; 62 | top: 0; 63 | } 64 | 65 | .top-row { 66 | position: sticky; 67 | top: 0; 68 | z-index: 1; 69 | } 70 | 71 | .top-row.auth ::deep a:first-child { 72 | flex: 1; 73 | text-align: right; 74 | width: 0; 75 | } 76 | 77 | .top-row, article { 78 | padding-left: 2rem !important; 79 | padding-right: 1.5rem !important; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Shared/NavMenu.razor: -------------------------------------------------------------------------------- 1 |  9 | 10 | 39 | 40 | @code { 41 | private bool collapseNavMenu = true; 42 | 43 | private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null; 44 | 45 | private void ToggleNavMenu() 46 | { 47 | collapseNavMenu = !collapseNavMenu; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/Shared/NavMenu.razor.css: -------------------------------------------------------------------------------- 1 | .navbar-toggler { 2 | background-color: rgba(255, 255, 255, 0.1); 3 | } 4 | 5 | .top-row { 6 | height: 3.5rem; 7 | background-color: rgba(0,0,0,0.4); 8 | } 9 | 10 | .navbar-brand { 11 | font-size: 1.1rem; 12 | } 13 | 14 | .oi { 15 | width: 2rem; 16 | font-size: 1.1rem; 17 | vertical-align: text-top; 18 | top: -2px; 19 | } 20 | 21 | .nav-item { 22 | font-size: 0.9rem; 23 | padding-bottom: 0.5rem; 24 | } 25 | 26 | .nav-item:first-of-type { 27 | padding-top: 1rem; 28 | } 29 | 30 | .nav-item:last-of-type { 31 | padding-bottom: 1rem; 32 | } 33 | 34 | .nav-item ::deep a { 35 | color: #d7d7d7; 36 | border-radius: 4px; 37 | height: 3rem; 38 | display: flex; 39 | align-items: center; 40 | line-height: 3rem; 41 | } 42 | 43 | .nav-item ::deep a.active { 44 | background-color: rgba(255,255,255,0.25); 45 | color: white; 46 | } 47 | 48 | .nav-item ::deep a:hover { 49 | background-color: rgba(255,255,255,0.1); 50 | color: white; 51 | } 52 | 53 | @media (min-width: 641px) { 54 | .navbar-toggler { 55 | display: none; 56 | } 57 | 58 | .collapse { 59 | /* Never collapse the sidebar for wide screens */ 60 | display: block; 61 | } 62 | 63 | .nav-scrollable { 64 | /* Allow sidebar to scroll for tall menus */ 65 | height: calc(100vh - 3.5rem); 66 | overflow-y: auto; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.AspNetCore.Components.WebAssembly.Http 8 | @using Microsoft.JSInterop 9 | @using KristofferStrube.Blazor.DOM 10 | @using KristofferStrube.Blazor.FileAPI.WasmExample 11 | @using KristofferStrube.Blazor.FileAPI.WasmExample.Shared 12 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/404.html: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Blazor FileAPI 6 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/app.css: -------------------------------------------------------------------------------- 1 | @import url('open-iconic/font/css/open-iconic-bootstrap.min.css'); 2 | 3 | html, body { 4 | font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 5 | } 6 | 7 | h1:focus { 8 | outline: none; 9 | } 10 | 11 | a, .btn-link { 12 | color: #0071c1; 13 | } 14 | 15 | .btn-primary { 16 | color: #fff; 17 | background-color: #1b6ec2; 18 | border-color: #1861ac; 19 | } 20 | 21 | .btn:focus, .btn:active:focus, .btn-link.nav-link:focus, .form-control:focus, .form-check-input:focus { 22 | box-shadow: 0 0 0 0.1rem white, 0 0 0 0.25rem #258cfb; 23 | } 24 | 25 | .content { 26 | padding-top: 1.1rem; 27 | } 28 | 29 | .valid.modified:not([type=checkbox]) { 30 | outline: 1px solid #26b050; 31 | } 32 | 33 | .invalid { 34 | outline: 1px solid red; 35 | } 36 | 37 | .validation-message { 38 | color: red; 39 | } 40 | 41 | #blazor-error-ui { 42 | background: lightyellow; 43 | bottom: 0; 44 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 45 | display: none; 46 | left: 0; 47 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 48 | position: fixed; 49 | width: 100%; 50 | z-index: 1000; 51 | } 52 | 53 | #blazor-error-ui .dismiss { 54 | cursor: pointer; 55 | position: absolute; 56 | right: 0.75rem; 57 | top: 0.5rem; 58 | } 59 | 60 | .blazor-error-boundary { 61 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 62 | padding: 1rem 1rem 1rem 3.7rem; 63 | color: white; 64 | } 65 | 66 | .blazor-error-boundary::after { 67 | content: "An error has occurred." 68 | } 69 | 70 | .loading-progress { 71 | position: relative; 72 | display: block; 73 | width: 8rem; 74 | height: 8rem; 75 | margin: 20vh auto 1rem auto; 76 | } 77 | 78 | .loading-progress circle { 79 | fill: none; 80 | stroke: #e0e0e0; 81 | stroke-width: 0.6rem; 82 | transform-origin: 50% 50%; 83 | transform: rotate(-90deg); 84 | } 85 | 86 | .loading-progress circle:last-child { 87 | stroke: #1b6ec2; 88 | stroke-dasharray: calc(3.141 * var(--blazor-load-percentage, 0%) * 0.8), 500%; 89 | transition: stroke-dasharray 0.05s ease-in-out; 90 | } 91 | 92 | .loading-progress-text { 93 | position: absolute; 94 | text-align: center; 95 | font-weight: bold; 96 | inset: calc(20vh + 3.25rem) 0 auto 0.2rem; 97 | } 98 | 99 | .loading-progress-text:after { 100 | content: var(--blazor-load-percentage-text, "Loading"); 101 | } 102 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/FONT-LICENSE: -------------------------------------------------------------------------------- 1 | SIL OPEN FONT LICENSE Version 1.1 2 | 3 | Copyright (c) 2014 Waybury 4 | 5 | PREAMBLE 6 | The goals of the Open Font License (OFL) are to stimulate worldwide 7 | development of collaborative font projects, to support the font creation 8 | efforts of academic and linguistic communities, and to provide a free and 9 | open framework in which fonts may be shared and improved in partnership 10 | with others. 11 | 12 | The OFL allows the licensed fonts to be used, studied, modified and 13 | redistributed freely as long as they are not sold by themselves. The 14 | fonts, including any derivative works, can be bundled, embedded, 15 | redistributed and/or sold with any software provided that any reserved 16 | names are not used by derivative works. The fonts and derivatives, 17 | however, cannot be released under any other type of license. The 18 | requirement for fonts to remain under this license does not apply 19 | to any document created using the fonts or their derivatives. 20 | 21 | DEFINITIONS 22 | "Font Software" refers to the set of files released by the Copyright 23 | Holder(s) under this license and clearly marked as such. This may 24 | include source files, build scripts and documentation. 25 | 26 | "Reserved Font Name" refers to any names specified as such after the 27 | copyright statement(s). 28 | 29 | "Original Version" refers to the collection of Font Software components as 30 | distributed by the Copyright Holder(s). 31 | 32 | "Modified Version" refers to any derivative made by adding to, deleting, 33 | or substituting -- in part or in whole -- any of the components of the 34 | Original Version, by changing formats or by porting the Font Software to a 35 | new environment. 36 | 37 | "Author" refers to any designer, engineer, programmer, technical 38 | writer or other person who contributed to the Font Software. 39 | 40 | PERMISSION & CONDITIONS 41 | Permission is hereby granted, free of charge, to any person obtaining 42 | a copy of the Font Software, to use, study, copy, merge, embed, modify, 43 | redistribute, and sell modified and unmodified copies of the Font 44 | Software, subject to the following conditions: 45 | 46 | 1) Neither the Font Software nor any of its individual components, 47 | in Original or Modified Versions, may be sold by itself. 48 | 49 | 2) Original or Modified Versions of the Font Software may be bundled, 50 | redistributed and/or sold with any software, provided that each copy 51 | contains the above copyright notice and this license. These can be 52 | included either as stand-alone text files, human-readable headers or 53 | in the appropriate machine-readable metadata fields within text or 54 | binary files as long as those fields can be easily viewed by the user. 55 | 56 | 3) No Modified Version of the Font Software may use the Reserved Font 57 | Name(s) unless explicit written permission is granted by the corresponding 58 | Copyright Holder. This restriction only applies to the primary font name as 59 | presented to the users. 60 | 61 | 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font 62 | Software shall not be used to promote, endorse or advertise any 63 | Modified Version, except to acknowledge the contribution(s) of the 64 | Copyright Holder(s) and the Author(s) or with their explicit written 65 | permission. 66 | 67 | 5) The Font Software, modified or unmodified, in part or in whole, 68 | must be distributed entirely under this license, and must not be 69 | distributed under any other license. The requirement for fonts to 70 | remain under this license does not apply to any document created 71 | using the Font Software. 72 | 73 | TERMINATION 74 | This license becomes null and void if any of the above conditions are 75 | not met. 76 | 77 | DISCLAIMER 78 | THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 79 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF 80 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 81 | OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE 82 | COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 83 | INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL 84 | DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 85 | FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM 86 | OTHER DEALINGS IN THE FONT SOFTWARE. 87 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/ICON-LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 Waybury 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/README.md: -------------------------------------------------------------------------------- 1 | [Open Iconic v1.1.1](http://useiconic.com/open) 2 | =========== 3 | 4 | ### Open Iconic is the open source sibling of [Iconic](http://useiconic.com). It is a hyper-legible collection of 223 icons with a tiny footprint—ready to use with Bootstrap and Foundation. [View the collection](http://useiconic.com/open#icons) 5 | 6 | 7 | 8 | ## What's in Open Iconic? 9 | 10 | * 223 icons designed to be legible down to 8 pixels 11 | * Super-light SVG files - 61.8 for the entire set 12 | * SVG sprite—the modern replacement for icon fonts 13 | * Webfont (EOT, OTF, SVG, TTF, WOFF), PNG and WebP formats 14 | * Webfont stylesheets (including versions for Bootstrap and Foundation) in CSS, LESS, SCSS and Stylus formats 15 | * PNG and WebP raster images in 8px, 16px, 24px, 32px, 48px and 64px. 16 | 17 | 18 | ## Getting Started 19 | 20 | #### For code samples and everything else you need to get started with Open Iconic, check out our [Icons](http://useiconic.com/open#icons) and [Reference](http://useiconic.com/open#reference) sections. 21 | 22 | ### General Usage 23 | 24 | #### Using Open Iconic's SVGs 25 | 26 | We like SVGs and we think they're the way to display icons on the web. Since Open Iconic are just basic SVGs, we suggest you display them like you would any other image (don't forget the `alt` attribute). 27 | 28 | ``` 29 | icon name 30 | ``` 31 | 32 | #### Using Open Iconic's SVG Sprite 33 | 34 | Open Iconic also comes in a SVG sprite which allows you to display all the icons in the set with a single request. It's like an icon font, without being a hack. 35 | 36 | Adding an icon from an SVG sprite is a little different than what you're used to, but it's still a piece of cake. *Tip: To make your icons easily style able, we suggest adding a general class to the* `` *tag and a unique class name for each different icon in the* `` *tag.* 37 | 38 | ``` 39 | 40 | 41 | 42 | ``` 43 | 44 | Sizing icons only needs basic CSS. All the icons are in a square format, so just set the `` tag with equal width and height dimensions. 45 | 46 | ``` 47 | .icon { 48 | width: 16px; 49 | height: 16px; 50 | } 51 | ``` 52 | 53 | Coloring icons is even easier. All you need to do is set the `fill` rule on the `` tag. 54 | 55 | ``` 56 | .icon-account-login { 57 | fill: #f00; 58 | } 59 | ``` 60 | 61 | To learn more about SVG Sprites, read [Chris Coyier's guide](http://css-tricks.com/svg-sprites-use-better-icon-fonts/). 62 | 63 | #### Using Open Iconic's Icon Font... 64 | 65 | 66 | ##### …with Bootstrap 67 | 68 | You can find our Bootstrap stylesheets in `font/css/open-iconic-bootstrap.{css, less, scss, styl}` 69 | 70 | 71 | ``` 72 | 73 | ``` 74 | 75 | 76 | ``` 77 | 78 | ``` 79 | 80 | ##### …with Foundation 81 | 82 | You can find our Foundation stylesheets in `font/css/open-iconic-foundation.{css, less, scss, styl}` 83 | 84 | ``` 85 | 86 | ``` 87 | 88 | 89 | ``` 90 | 91 | ``` 92 | 93 | ##### …on its own 94 | 95 | You can find our default stylesheets in `font/css/open-iconic.{css, less, scss, styl}` 96 | 97 | ``` 98 | 99 | ``` 100 | 101 | ``` 102 | 103 | ``` 104 | 105 | 106 | ## License 107 | 108 | ### Icons 109 | 110 | All code (including SVG markup) is under the [MIT License](http://opensource.org/licenses/MIT). 111 | 112 | ### Fonts 113 | 114 | All fonts are under the [SIL Licensed](http://scripts.sil.org/cms/scripts/page.php?item_id=OFL_web). 115 | -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/css/open-iconic-bootstrap.min.css: -------------------------------------------------------------------------------- 1 | @font-face{font-family:Icons;src:url(../fonts/open-iconic.eot);src:url(../fonts/open-iconic.eot?#iconic-sm) format('embedded-opentype'),url(../fonts/open-iconic.woff) format('woff'),url(../fonts/open-iconic.ttf) format('truetype'),url(../fonts/open-iconic.otf) format('opentype'),url(../fonts/open-iconic.svg#iconic-sm) format('svg');font-weight:400;font-style:normal}.oi{position:relative;top:1px;display:inline-block;speak:none;font-family:Icons;font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.oi:empty:before{width:1em;text-align:center;box-sizing:content-box}.oi.oi-align-center:before{text-align:center}.oi.oi-align-left:before{text-align:left}.oi.oi-align-right:before{text-align:right}.oi.oi-flip-horizontal:before{-webkit-transform:scale(-1,1);-ms-transform:scale(-1,1);transform:scale(-1,1)}.oi.oi-flip-vertical:before{-webkit-transform:scale(1,-1);-ms-transform:scale(-1,1);transform:scale(1,-1)}.oi.oi-flip-horizontal-vertical:before{-webkit-transform:scale(-1,-1);-ms-transform:scale(-1,1);transform:scale(-1,-1)}.oi-account-login:before{content:'\e000'}.oi-account-logout:before{content:'\e001'}.oi-action-redo:before{content:'\e002'}.oi-action-undo:before{content:'\e003'}.oi-align-center:before{content:'\e004'}.oi-align-left:before{content:'\e005'}.oi-align-right:before{content:'\e006'}.oi-aperture:before{content:'\e007'}.oi-arrow-bottom:before{content:'\e008'}.oi-arrow-circle-bottom:before{content:'\e009'}.oi-arrow-circle-left:before{content:'\e00a'}.oi-arrow-circle-right:before{content:'\e00b'}.oi-arrow-circle-top:before{content:'\e00c'}.oi-arrow-left:before{content:'\e00d'}.oi-arrow-right:before{content:'\e00e'}.oi-arrow-thick-bottom:before{content:'\e00f'}.oi-arrow-thick-left:before{content:'\e010'}.oi-arrow-thick-right:before{content:'\e011'}.oi-arrow-thick-top:before{content:'\e012'}.oi-arrow-top:before{content:'\e013'}.oi-audio-spectrum:before{content:'\e014'}.oi-audio:before{content:'\e015'}.oi-badge:before{content:'\e016'}.oi-ban:before{content:'\e017'}.oi-bar-chart:before{content:'\e018'}.oi-basket:before{content:'\e019'}.oi-battery-empty:before{content:'\e01a'}.oi-battery-full:before{content:'\e01b'}.oi-beaker:before{content:'\e01c'}.oi-bell:before{content:'\e01d'}.oi-bluetooth:before{content:'\e01e'}.oi-bold:before{content:'\e01f'}.oi-bolt:before{content:'\e020'}.oi-book:before{content:'\e021'}.oi-bookmark:before{content:'\e022'}.oi-box:before{content:'\e023'}.oi-briefcase:before{content:'\e024'}.oi-british-pound:before{content:'\e025'}.oi-browser:before{content:'\e026'}.oi-brush:before{content:'\e027'}.oi-bug:before{content:'\e028'}.oi-bullhorn:before{content:'\e029'}.oi-calculator:before{content:'\e02a'}.oi-calendar:before{content:'\e02b'}.oi-camera-slr:before{content:'\e02c'}.oi-caret-bottom:before{content:'\e02d'}.oi-caret-left:before{content:'\e02e'}.oi-caret-right:before{content:'\e02f'}.oi-caret-top:before{content:'\e030'}.oi-cart:before{content:'\e031'}.oi-chat:before{content:'\e032'}.oi-check:before{content:'\e033'}.oi-chevron-bottom:before{content:'\e034'}.oi-chevron-left:before{content:'\e035'}.oi-chevron-right:before{content:'\e036'}.oi-chevron-top:before{content:'\e037'}.oi-circle-check:before{content:'\e038'}.oi-circle-x:before{content:'\e039'}.oi-clipboard:before{content:'\e03a'}.oi-clock:before{content:'\e03b'}.oi-cloud-download:before{content:'\e03c'}.oi-cloud-upload:before{content:'\e03d'}.oi-cloud:before{content:'\e03e'}.oi-cloudy:before{content:'\e03f'}.oi-code:before{content:'\e040'}.oi-cog:before{content:'\e041'}.oi-collapse-down:before{content:'\e042'}.oi-collapse-left:before{content:'\e043'}.oi-collapse-right:before{content:'\e044'}.oi-collapse-up:before{content:'\e045'}.oi-command:before{content:'\e046'}.oi-comment-square:before{content:'\e047'}.oi-compass:before{content:'\e048'}.oi-contrast:before{content:'\e049'}.oi-copywriting:before{content:'\e04a'}.oi-credit-card:before{content:'\e04b'}.oi-crop:before{content:'\e04c'}.oi-dashboard:before{content:'\e04d'}.oi-data-transfer-download:before{content:'\e04e'}.oi-data-transfer-upload:before{content:'\e04f'}.oi-delete:before{content:'\e050'}.oi-dial:before{content:'\e051'}.oi-document:before{content:'\e052'}.oi-dollar:before{content:'\e053'}.oi-double-quote-sans-left:before{content:'\e054'}.oi-double-quote-sans-right:before{content:'\e055'}.oi-double-quote-serif-left:before{content:'\e056'}.oi-double-quote-serif-right:before{content:'\e057'}.oi-droplet:before{content:'\e058'}.oi-eject:before{content:'\e059'}.oi-elevator:before{content:'\e05a'}.oi-ellipses:before{content:'\e05b'}.oi-envelope-closed:before{content:'\e05c'}.oi-envelope-open:before{content:'\e05d'}.oi-euro:before{content:'\e05e'}.oi-excerpt:before{content:'\e05f'}.oi-expand-down:before{content:'\e060'}.oi-expand-left:before{content:'\e061'}.oi-expand-right:before{content:'\e062'}.oi-expand-up:before{content:'\e063'}.oi-external-link:before{content:'\e064'}.oi-eye:before{content:'\e065'}.oi-eyedropper:before{content:'\e066'}.oi-file:before{content:'\e067'}.oi-fire:before{content:'\e068'}.oi-flag:before{content:'\e069'}.oi-flash:before{content:'\e06a'}.oi-folder:before{content:'\e06b'}.oi-fork:before{content:'\e06c'}.oi-fullscreen-enter:before{content:'\e06d'}.oi-fullscreen-exit:before{content:'\e06e'}.oi-globe:before{content:'\e06f'}.oi-graph:before{content:'\e070'}.oi-grid-four-up:before{content:'\e071'}.oi-grid-three-up:before{content:'\e072'}.oi-grid-two-up:before{content:'\e073'}.oi-hard-drive:before{content:'\e074'}.oi-header:before{content:'\e075'}.oi-headphones:before{content:'\e076'}.oi-heart:before{content:'\e077'}.oi-home:before{content:'\e078'}.oi-image:before{content:'\e079'}.oi-inbox:before{content:'\e07a'}.oi-infinity:before{content:'\e07b'}.oi-info:before{content:'\e07c'}.oi-italic:before{content:'\e07d'}.oi-justify-center:before{content:'\e07e'}.oi-justify-left:before{content:'\e07f'}.oi-justify-right:before{content:'\e080'}.oi-key:before{content:'\e081'}.oi-laptop:before{content:'\e082'}.oi-layers:before{content:'\e083'}.oi-lightbulb:before{content:'\e084'}.oi-link-broken:before{content:'\e085'}.oi-link-intact:before{content:'\e086'}.oi-list-rich:before{content:'\e087'}.oi-list:before{content:'\e088'}.oi-location:before{content:'\e089'}.oi-lock-locked:before{content:'\e08a'}.oi-lock-unlocked:before{content:'\e08b'}.oi-loop-circular:before{content:'\e08c'}.oi-loop-square:before{content:'\e08d'}.oi-loop:before{content:'\e08e'}.oi-magnifying-glass:before{content:'\e08f'}.oi-map-marker:before{content:'\e090'}.oi-map:before{content:'\e091'}.oi-media-pause:before{content:'\e092'}.oi-media-play:before{content:'\e093'}.oi-media-record:before{content:'\e094'}.oi-media-skip-backward:before{content:'\e095'}.oi-media-skip-forward:before{content:'\e096'}.oi-media-step-backward:before{content:'\e097'}.oi-media-step-forward:before{content:'\e098'}.oi-media-stop:before{content:'\e099'}.oi-medical-cross:before{content:'\e09a'}.oi-menu:before{content:'\e09b'}.oi-microphone:before{content:'\e09c'}.oi-minus:before{content:'\e09d'}.oi-monitor:before{content:'\e09e'}.oi-moon:before{content:'\e09f'}.oi-move:before{content:'\e0a0'}.oi-musical-note:before{content:'\e0a1'}.oi-paperclip:before{content:'\e0a2'}.oi-pencil:before{content:'\e0a3'}.oi-people:before{content:'\e0a4'}.oi-person:before{content:'\e0a5'}.oi-phone:before{content:'\e0a6'}.oi-pie-chart:before{content:'\e0a7'}.oi-pin:before{content:'\e0a8'}.oi-play-circle:before{content:'\e0a9'}.oi-plus:before{content:'\e0aa'}.oi-power-standby:before{content:'\e0ab'}.oi-print:before{content:'\e0ac'}.oi-project:before{content:'\e0ad'}.oi-pulse:before{content:'\e0ae'}.oi-puzzle-piece:before{content:'\e0af'}.oi-question-mark:before{content:'\e0b0'}.oi-rain:before{content:'\e0b1'}.oi-random:before{content:'\e0b2'}.oi-reload:before{content:'\e0b3'}.oi-resize-both:before{content:'\e0b4'}.oi-resize-height:before{content:'\e0b5'}.oi-resize-width:before{content:'\e0b6'}.oi-rss-alt:before{content:'\e0b7'}.oi-rss:before{content:'\e0b8'}.oi-script:before{content:'\e0b9'}.oi-share-boxed:before{content:'\e0ba'}.oi-share:before{content:'\e0bb'}.oi-shield:before{content:'\e0bc'}.oi-signal:before{content:'\e0bd'}.oi-signpost:before{content:'\e0be'}.oi-sort-ascending:before{content:'\e0bf'}.oi-sort-descending:before{content:'\e0c0'}.oi-spreadsheet:before{content:'\e0c1'}.oi-star:before{content:'\e0c2'}.oi-sun:before{content:'\e0c3'}.oi-tablet:before{content:'\e0c4'}.oi-tag:before{content:'\e0c5'}.oi-tags:before{content:'\e0c6'}.oi-target:before{content:'\e0c7'}.oi-task:before{content:'\e0c8'}.oi-terminal:before{content:'\e0c9'}.oi-text:before{content:'\e0ca'}.oi-thumb-down:before{content:'\e0cb'}.oi-thumb-up:before{content:'\e0cc'}.oi-timer:before{content:'\e0cd'}.oi-transfer:before{content:'\e0ce'}.oi-trash:before{content:'\e0cf'}.oi-underline:before{content:'\e0d0'}.oi-vertical-align-bottom:before{content:'\e0d1'}.oi-vertical-align-center:before{content:'\e0d2'}.oi-vertical-align-top:before{content:'\e0d3'}.oi-video:before{content:'\e0d4'}.oi-volume-high:before{content:'\e0d5'}.oi-volume-low:before{content:'\e0d6'}.oi-volume-off:before{content:'\e0d7'}.oi-warning:before{content:'\e0d8'}.oi-wifi:before{content:'\e0d9'}.oi-wrench:before{content:'\e0da'}.oi-x:before{content:'\e0db'}.oi-yen:before{content:'\e0dc'}.oi-zoom-in:before{content:'\e0dd'}.oi-zoom-out:before{content:'\e0de'} -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.eot -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.otf -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.ttf -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/css/open-iconic/font/fonts/open-iconic.woff -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/favicon.png -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/icon-192.png -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/images/mountain.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KristofferStrube/Blazor.FileAPI/8f90013a275e2561832f80d141b8f8bae01abb6c/samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/images/mountain.jpg -------------------------------------------------------------------------------- /samples/KristofferStrube.Blazor.FileAPI.WasmExample/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Blazor FileAPI 8 | 9 | 10 | 32 | 43 | 44 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 |
58 | 59 | 60 | 61 | 62 |
63 |
64 | 65 |
66 | An unhandled error has occurred. 67 | Reload 68 | 🗙 69 |
70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/BaseJSWrapper.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.WebIDL; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.FileAPI; 5 | 6 | /// 7 | /// A base class for all wrappers in Blazor.FileAPI. 8 | /// 9 | public abstract class BaseJSWrapper : IJSWrapper 10 | { 11 | /// 12 | /// A lazily loaded task that evaluates to a helper module instance from the Blazor.FileAPI library. 13 | /// 14 | protected readonly Lazy> helperTask; 15 | 16 | /// 17 | public IJSRuntime JSRuntime { get; } 18 | /// 19 | public IJSObjectReference JSReference { get; } 20 | /// 21 | public bool DisposesJSReference { get; } 22 | 23 | /// 24 | /// Constructs a wrapper instance for an equivalent JS instance. 25 | /// 26 | /// An instance. 27 | /// A JS reference to an existing JS instance that should be wrapped. 28 | /// The options for constructing this wrapper. 29 | internal BaseJSWrapper(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) 30 | { 31 | helperTask = new(jSRuntime.GetHelperAsync); 32 | JSRuntime = jSRuntime; 33 | JSReference = jSReference; 34 | DisposesJSReference = options.DisposesJSReference; 35 | } 36 | 37 | /// 38 | public async ValueTask DisposeAsync() 39 | { 40 | if (helperTask.IsValueCreated) 41 | { 42 | IJSObjectReference module = await helperTask.Value; 43 | await module.DisposeAsync(); 44 | } 45 | await IJSWrapper.DisposeJSReference(this); 46 | GC.SuppressFinalize(this); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Blob.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.Streams; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.FileAPI; 6 | 7 | /// 8 | [IJSWrapperConverter] 9 | public class BlobInProcess : Blob, IJSInProcessCreatable 10 | { 11 | /// 12 | public new IJSInProcessObjectReference JSReference { get; } 13 | 14 | /// 15 | /// A helper module instance from the Blazor.FileAPI library. 16 | /// 17 | protected IJSInProcessObjectReference InProcessHelper { get; } 18 | 19 | /// 20 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 21 | { 22 | return await CreateAsync(jSRuntime, jSReference, new()); 23 | } 24 | 25 | /// 26 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, CreationOptions options) 27 | { 28 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(); 29 | return new BlobInProcess(jSRuntime, inProcessHelper, jSReference, options); 30 | } 31 | 32 | /// 33 | /// Constructs a wrapper instance using the standard constructor. 34 | /// 35 | /// An instance. 36 | /// The parts that will make the new . 37 | /// Options for constructing the new Blob which includes MIME type and line endings settings. 38 | /// 39 | public static new async Task CreateAsync(IJSRuntime jSRuntime, IList? blobParts = null, BlobPropertyBag? options = null) 40 | { 41 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(); 42 | object?[]? jsBlobParts = blobParts?.Select(blobPart => blobPart.Part switch 43 | { 44 | byte[] part => part, 45 | Blob part => part.JSReference, 46 | _ => blobPart.Part 47 | }) 48 | .ToArray(); 49 | IJSInProcessObjectReference jSInstance = await inProcessHelper.InvokeAsync("constructBlob", jsBlobParts, options); 50 | return new BlobInProcess(jSRuntime, inProcessHelper, jSInstance, new() { DisposesJSReference = true }); 51 | } 52 | 53 | /// 54 | protected internal BlobInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) 55 | { 56 | JSReference = jSReference; 57 | InProcessHelper = inProcessHelper; 58 | } 59 | 60 | /// 61 | /// Creates a new from the . 62 | /// 63 | /// A new wrapper for a 64 | public new async Task StreamAsync() 65 | { 66 | IJSInProcessObjectReference jSInstance = JSReference.Invoke("stream"); 67 | return await ReadableStreamInProcess.CreateAsync(JSRuntime, jSInstance, new() { DisposesJSReference = true }); 68 | } 69 | 70 | /// 71 | /// The size of this blob. 72 | /// 73 | /// A representing the size of the blob in bytes. 74 | public ulong Size => InProcessHelper.Invoke("getAttribute", JSReference, "size"); 75 | 76 | /// 77 | /// The media type of this blob. This is either a parseable MIME type or an empty string. 78 | /// 79 | /// The MIME type of this blob. 80 | public string Type => InProcessHelper.Invoke("getAttribute", JSReference, "type"); 81 | 82 | /// 83 | /// Gets some range of the content of a as a new . 84 | /// 85 | /// The start index of the range. If or negative then 0 is assumed. 86 | /// The start index of the range. If or larger than the size of the original then the size of the original is assumed. 87 | /// An optional MIME type of the new . If then the MIME type of the original is used. 88 | /// A new . 89 | public BlobInProcess Slice(long? start = null, long? end = null, string? contentType = null) 90 | { 91 | start ??= 0; 92 | end ??= (long)Size; 93 | IJSInProcessObjectReference jSInstance = JSReference.Invoke("slice", start, end, contentType); 94 | return new BlobInProcess(JSRuntime, InProcessHelper, jSInstance, new() { DisposesJSReference = true }); 95 | } 96 | 97 | /// 98 | public new async ValueTask DisposeAsync() 99 | { 100 | await InProcessHelper.DisposeAsync(); 101 | await base.DisposeAsync(); 102 | GC.SuppressFinalize(this); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Blob.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.Streams; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.FileAPI; 6 | 7 | /// 8 | /// A object refers to a byte sequence, 9 | /// and has a attribute which is the total number of bytes in the byte sequence, 10 | /// and a attribute, which is an ASCII-encoded string in lower case representing the media type of the byte sequence. 11 | /// 12 | /// See the API definition here 13 | [IJSWrapperConverter] 14 | public class Blob : BaseJSWrapper, IJSCreatable 15 | { 16 | /// 17 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 18 | { 19 | return await CreateAsync(jSRuntime, jSReference, new()); 20 | } 21 | 22 | /// 23 | public static Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) 24 | { 25 | return Task.FromResult(new Blob(jSRuntime, jSReference, options)); 26 | } 27 | 28 | /// 29 | /// Constructs a wrapper instance for a given JS Instance of a . 30 | /// 31 | /// An instance. 32 | /// A JS reference to an existing . 33 | /// A wrapper instance for a . 34 | [Obsolete("This will be removed in the next major release as all creator methods should be asynchronous for uniformity. Use CreateAsync instead.")] 35 | public static Blob Create(IJSRuntime jSRuntime, IJSObjectReference jSReference) 36 | { 37 | return new Blob(jSRuntime, jSReference, new()); 38 | } 39 | 40 | /// 41 | /// Constructs a wrapper instance using the standard constructor. 42 | /// 43 | /// An instance. 44 | /// The parts that will make the new . 45 | /// Options for constructing the new Blob which includes MIME type and line endings settings. 46 | /// 47 | public static async Task CreateAsync(IJSRuntime jSRuntime, IList? blobParts = null, BlobPropertyBag? options = null) 48 | { 49 | IJSObjectReference helper = await jSRuntime.GetHelperAsync(); 50 | object?[]? jsBlobParts = blobParts?.Select(blobPart => blobPart.Part switch 51 | { 52 | byte[] part => part, 53 | Blob part => part.JSReference, 54 | _ => blobPart.Part 55 | }) 56 | .ToArray(); 57 | IJSObjectReference jSInstance = await helper.InvokeAsync("constructBlob", jsBlobParts, options); 58 | return new Blob(jSRuntime, jSInstance, new() { DisposesJSReference = true }); 59 | } 60 | 61 | /// 62 | protected Blob(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) { } 63 | 64 | /// 65 | /// The size of this blob. 66 | /// 67 | /// A representing the size of the blob in bytes. 68 | public async Task GetSizeAsync() 69 | { 70 | IJSObjectReference helper = await helperTask.Value; 71 | return await helper.InvokeAsync("getAttribute", JSReference, "size"); 72 | } 73 | 74 | /// 75 | /// The media type of this blob. This is either a parseable MIME type or an empty string. 76 | /// 77 | /// The MIME type of this blob. 78 | public async Task GetTypeAsync() 79 | { 80 | IJSObjectReference helper = await helperTask.Value; 81 | return await helper.InvokeAsync("getAttribute", JSReference, "type"); 82 | } 83 | 84 | /// 85 | /// Gets some range of the content of a as a new . 86 | /// 87 | /// The start index of the range. If or negative then 0 is assumed. 88 | /// The start index of the range. If or larger than the size of the original then the size of the original is assumed. 89 | /// An optional MIME type of the new . If then the MIME type of the original is used. 90 | /// A new . 91 | public async Task SliceAsync(long? start = null, long? end = null, string? contentType = null) 92 | { 93 | start ??= 0; 94 | end ??= (long)await GetSizeAsync(); 95 | IJSObjectReference jSInstance = await JSReference.InvokeAsync("slice", start, end, contentType); 96 | return new Blob(JSRuntime, jSInstance, new() { DisposesJSReference = true }); 97 | } 98 | 99 | /// 100 | /// Creates a new from the . 101 | /// 102 | /// A new wrapper for a 103 | public async Task StreamAsync() 104 | { 105 | IJSObjectReference jSInstance = await JSReference.InvokeAsync("stream"); 106 | return await ReadableStream.CreateAsync(JSRuntime, jSInstance, new() { DisposesJSReference = true }); 107 | } 108 | 109 | /// 110 | /// The content of the blob as a string. 111 | /// 112 | /// The content of the file in UTF-8 format. 113 | public async Task TextAsync() 114 | { 115 | return await JSReference.InvokeAsync("text"); 116 | } 117 | 118 | /// 119 | /// The content of the blob as a byte array. 120 | /// 121 | /// All bytes in the blob. 122 | public async Task ArrayBufferAsync() 123 | { 124 | IJSObjectReference jSInstance = await JSReference.InvokeAsync("arrayBuffer"); 125 | IJSObjectReference helper = await helperTask.Value; 126 | return await helper.InvokeAsync("arrayBuffer", jSInstance); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Converters/DateTimeConverter.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace KristofferStrube.Blazor.FileAPI; 5 | 6 | internal class DateTimeConverter : JsonConverter 7 | { 8 | public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 9 | { 10 | return reader.TryGetUInt64(out ulong jsonValue) 11 | ? DateTime.UnixEpoch.AddMilliseconds(jsonValue) 12 | : throw new JsonException($"string {reader.GetString()} could not be parsed as a long."); 13 | } 14 | 15 | public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) 16 | { 17 | writer.WriteNumberValue(value.Subtract(DateTime.UnixEpoch).TotalMilliseconds); 18 | } 19 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Converters/EnumDescriptionConverter.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Reflection; 3 | using System.Text.Json; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace KristofferStrube.Blazor.FileAPI; 7 | 8 | #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. 9 | #pragma warning disable CS8603 // Possible null reference return. 10 | #pragma warning disable CS8604 // Possible null reference argument. 11 | #pragma warning disable CS8602 // Dereference of a possibly null reference. 12 | internal class EnumDescriptionConverter : JsonConverter where T : IComparable, IFormattable, IConvertible 13 | { 14 | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) 15 | { 16 | string jsonValue = reader.GetString(); 17 | 18 | foreach (FieldInfo? fi in typeToConvert.GetFields()) 19 | { 20 | var description = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false); 21 | 22 | if (description != null) 23 | { 24 | if (description.Description == jsonValue) 25 | { 26 | return (T)fi.GetValue(null); 27 | } 28 | } 29 | } 30 | throw new JsonException($"string {jsonValue} was not found as a description in the enum {typeToConvert}"); 31 | } 32 | 33 | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) 34 | { 35 | FieldInfo fi = value.GetType().GetField(value.ToString()); 36 | 37 | var description = (DescriptionAttribute)fi.GetCustomAttribute(typeof(DescriptionAttribute), false); 38 | 39 | writer.WriteStringValue(description.Description); 40 | } 41 | } 42 | #pragma warning restore CS8602 // Dereference of a possibly null reference. 43 | #pragma warning restore CS8604 // Possible null reference argument. 44 | #pragma warning restore CS8603 // Possible null reference return. 45 | #pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Enums/EndingType.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel; 2 | using System.Text.Json.Serialization; 3 | 4 | namespace KristofferStrube.Blazor.FileAPI; 5 | 6 | /// 7 | /// It controls how line endings are handled in elements within s 8 | /// 9 | /// 10 | /// EndingType browser specs 11 | /// 12 | [JsonConverter(typeof(EnumDescriptionConverter))] 13 | public enum EndingType 14 | { 15 | /// 16 | /// Line endings in elements within s remain unchanged, with no conversion applied, preserving the original format. 17 | /// 18 | [Description("transparent")] 19 | Transparent, 20 | 21 | /// 22 | /// Line endings in elements within s are converted to the platform's native format (\n or \r\n), ensuring consistency with the system's convention. 23 | /// 24 | [Description("native")] 25 | Native, 26 | } 27 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Extensions/IJSRuntimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileAPI; 4 | 5 | internal static class IJSRuntimeExtensions 6 | { 7 | internal static async Task GetHelperAsync(this IJSRuntime jSRuntime) 8 | { 9 | return await jSRuntime.InvokeAsync( 10 | "import", "./_content/KristofferStrube.Blazor.FileAPI/KristofferStrube.Blazor.FileAPI.js"); 11 | } 12 | internal static async Task GetInProcessHelperAsync(this IJSRuntime jSRuntime) 13 | { 14 | return await jSRuntime.InvokeAsync( 15 | "import", "./_content/KristofferStrube.Blazor.FileAPI/KristofferStrube.Blazor.FileAPI.js"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Extensions/IServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.FileAPI; 5 | 6 | /// 7 | /// Contains extension methods for adding services to a . 8 | /// 9 | public static class IServiceCollectionExtensions 10 | { 11 | /// 12 | /// Adds an to the service collection. 13 | /// 14 | /// The service collection. 15 | public static IServiceCollection AddURLService(this IServiceCollection serviceCollection) 16 | { 17 | return serviceCollection.AddScoped(); 18 | } 19 | 20 | /// 21 | /// Adds an to the service collection. 22 | /// 23 | /// The service collection. 24 | public static IServiceCollection AddURLServiceInProcess(this IServiceCollection serviceCollection) 25 | { 26 | return serviceCollection.AddScoped(sp => new URLServiceInProcess((IJSInProcessRuntime)sp.GetRequiredService())); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/File.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.Streams; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.FileAPI; 6 | 7 | /// 8 | [IJSWrapperConverter] 9 | public class FileInProcess : File, IJSInProcessCreatable 10 | { 11 | /// 12 | public new IJSInProcessObjectReference JSReference { get; } 13 | 14 | /// 15 | /// A helper module instance from the Blazor.FileAPI library. 16 | /// 17 | protected IJSInProcessObjectReference InProcessHelper { get; } 18 | 19 | /// 20 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 21 | { 22 | return await CreateAsync(jSRuntime, jSReference, new()); 23 | } 24 | 25 | /// 26 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, CreationOptions options) 27 | { 28 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(); 29 | return new FileInProcess(jSRuntime, inProcessHelper, jSReference, options); 30 | } 31 | 32 | /// 33 | /// Constructs a wrapper instance using the standard constructor. 34 | /// 35 | /// An instance. 36 | /// The bits that will make the new . 37 | /// The name of the new file. 38 | /// Options for constructing the new Blob which includes MIME type, line endings, and last modified date. 39 | /// 40 | public static new async Task CreateAsync(IJSRuntime jSRuntime, IList fileBits, string fileName, FilePropertyBag? options = null) 41 | { 42 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(); 43 | object?[]? jsFileBits = fileBits.Select(blobPart => blobPart.Part switch 44 | { 45 | byte[] part => part, 46 | Blob part => part.JSReference, 47 | _ => blobPart.Part 48 | }) 49 | .ToArray(); 50 | IJSInProcessObjectReference jSInstance = await inProcessHelper.InvokeAsync("constructFile", jsFileBits, fileName, options); 51 | return new FileInProcess(jSRuntime, inProcessHelper, jSInstance, new() { DisposesJSReference = true }); 52 | } 53 | 54 | /// 55 | protected FileInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) 56 | { 57 | JSReference = jSReference; 58 | InProcessHelper = inProcessHelper; 59 | } 60 | 61 | /// 62 | /// Creates a new from the . 63 | /// 64 | /// A new wrapper for a 65 | public new async Task StreamAsync() 66 | { 67 | IJSInProcessObjectReference jSInstance = JSReference.Invoke("stream"); 68 | return await ReadableStreamInProcess.CreateAsync(JSRuntime, jSInstance, new() { DisposesJSReference = true }); 69 | } 70 | 71 | /// 72 | /// The size of this blob. 73 | /// 74 | /// A representing the size of the blob in bytes. 75 | public ulong Size => InProcessHelper.Invoke("getAttribute", JSReference, "size"); 76 | 77 | /// 78 | /// The media type of this blob. This is either a parseable MIME type or an empty string. 79 | /// 80 | /// The MIME type of this blob. 81 | public string Type => InProcessHelper.Invoke("getAttribute", JSReference, "type"); 82 | 83 | /// 84 | /// Gets some range of the content of a as a new . 85 | /// 86 | /// The start index of the range. If or negative then 0 is assumed. 87 | /// The start index of the range. If or larger than the size of the original then the size of the original is assumed. 88 | /// An optional MIME type of the new . If then the MIME type of the original is used. 89 | /// A new . 90 | public BlobInProcess Slice(long? start = null, long? end = null, string? contentType = null) 91 | { 92 | start ??= 0; 93 | end ??= (long)Size; 94 | IJSInProcessObjectReference jSInstance = JSReference.Invoke("slice", start, end, contentType); 95 | return new BlobInProcess(JSRuntime, InProcessHelper, jSInstance, new() { DisposesJSReference = true }); 96 | } 97 | 98 | /// 99 | /// The name of the file including file extension. 100 | /// 101 | /// The file name. 102 | public string Name => InProcessHelper.Invoke("getAttribute", JSReference, "name"); 103 | 104 | /// 105 | /// The time that the file was last modified. 106 | /// 107 | /// A new object representing when the file was last modified. 108 | public DateTime LastModified => DateTime.UnixEpoch.AddMilliseconds(InProcessHelper.Invoke("getAttribute", JSReference, "lastModified")); 109 | 110 | /// 111 | public new async ValueTask DisposeAsync() 112 | { 113 | await InProcessHelper.DisposeAsync(); 114 | await base.DisposeAsync(); 115 | GC.SuppressFinalize(this); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/File.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.WebIDL; 2 | using Microsoft.JSInterop; 3 | 4 | namespace KristofferStrube.Blazor.FileAPI; 5 | 6 | /// 7 | /// A object is a object with a attribute, which is a string; 8 | /// it can be created within the web application via a constructor, 9 | /// or is a reference to a byte sequence from a file from the underlying (OS) file system. 10 | /// 11 | /// See the API definition here 12 | [IJSWrapperConverter] 13 | public class File : Blob, IJSCreatable 14 | { 15 | /// 16 | public static new async Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 17 | { 18 | return await CreateAsync(jSRuntime, jSReference, new()); 19 | } 20 | 21 | /// 22 | public static new Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) 23 | { 24 | return Task.FromResult(new File(jSRuntime, jSReference, options)); 25 | } 26 | 27 | /// 28 | /// Constructs a wrapper instance for a given JS Instance of a . 29 | /// 30 | /// An instance. 31 | /// A JS reference to an existing . 32 | /// A wrapper instance for a . 33 | [Obsolete("This will be removed in the next major release as all creator methods should be asynchronous for uniformity. Use CreateAsync instead.")] 34 | public static new File Create(IJSRuntime jSRuntime, IJSObjectReference jSReference) 35 | { 36 | return new File(jSRuntime, jSReference, new()); 37 | } 38 | 39 | /// 40 | /// Constructs a wrapper instance using the standard constructor. 41 | /// 42 | /// An instance. 43 | /// The bits that will make the new . 44 | /// The name of the new file. 45 | /// Options for constructing the new Blob which includes MIME type, line endings, and last modified date. 46 | /// 47 | public static async Task CreateAsync(IJSRuntime jSRuntime, IList fileBits, string fileName, FilePropertyBag? options = null) 48 | { 49 | IJSObjectReference helper = await jSRuntime.GetHelperAsync(); 50 | object?[]? jsFileBits = fileBits.Select(blobPart => blobPart.Part switch 51 | { 52 | byte[] part => part, 53 | Blob part => part.JSReference, 54 | _ => blobPart.Part 55 | }) 56 | .ToArray(); 57 | IJSObjectReference jSInstance = await helper.InvokeAsync("constructFile", jsFileBits, fileName, options); 58 | return new File(jSRuntime, jSInstance, new() { DisposesJSReference = true }); 59 | } 60 | 61 | /// 62 | protected File(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) { } 63 | 64 | /// 65 | /// The name of the file including file extension. 66 | /// 67 | /// The file name. 68 | public async Task GetNameAsync() 69 | { 70 | IJSObjectReference helper = await helperTask.Value; 71 | return await helper.InvokeAsync("getAttribute", JSReference, "name"); 72 | } 73 | 74 | /// 75 | /// The time that the file was last modified. 76 | /// 77 | /// A new object representing when the file was last modified. 78 | public async Task GetLastModifiedAsync() 79 | { 80 | IJSObjectReference helper = await helperTask.Value; 81 | return DateTime.UnixEpoch.AddMilliseconds(await helper.InvokeAsync("getAttribute", JSReference, "lastModified")); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/FileReader.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.DOM; 2 | using KristofferStrube.Blazor.DOM.Extensions; 3 | using KristofferStrube.Blazor.WebIDL; 4 | using Microsoft.JSInterop; 5 | using System.Text.Json.Serialization; 6 | 7 | namespace KristofferStrube.Blazor.FileAPI; 8 | 9 | /// 10 | [IJSWrapperConverter] 11 | public class FileReaderInProcess : FileReader, IJSInProcessCreatable, IEventTargetInProcess 12 | { 13 | /// 14 | public new IJSInProcessObjectReference JSReference { get; set; } 15 | 16 | /// 17 | /// A helper module instance from the Blazor.FileAPI library. 18 | /// 19 | protected IJSInProcessObjectReference InProcessHelper { get; } 20 | 21 | /// 22 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 23 | { 24 | return await CreateAsync(jSRuntime, jSReference, new()); 25 | } 26 | 27 | /// 28 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, CreationOptions options) 29 | { 30 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(); 31 | return new FileReaderInProcess(jSRuntime, inProcessHelper, jSReference, options); 32 | } 33 | 34 | /// 35 | /// Constructs a wrapper instance using the standard constructor. 36 | /// 37 | /// An instance. 38 | /// A wrapper instance for a . 39 | public static new async Task CreateAsync(IJSRuntime jSRuntime) 40 | { 41 | IJSInProcessObjectReference inProcessHelper = await jSRuntime.GetInProcessHelperAsync(); 42 | IJSInProcessObjectReference jSInstance = await inProcessHelper.InvokeAsync("constructFileReader"); 43 | FileReaderInProcess fileReaderInProcess = new(jSRuntime, inProcessHelper, jSInstance, new() { DisposesJSReference = true }); 44 | await inProcessHelper.InvokeVoidAsync("registerEventHandlers", DotNetObjectReference.Create(fileReaderInProcess), jSInstance); 45 | return fileReaderInProcess; 46 | } 47 | 48 | /// 49 | protected FileReaderInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) 50 | { 51 | JSReference = jSReference; 52 | InProcessHelper = inProcessHelper; 53 | } 54 | 55 | /// 56 | /// Starts a new read for some as an [] which can be read from once the load has ended which can be checked by setting the action . 57 | /// 58 | /// The that should be read asynchronously. 59 | /// 60 | public void ReadAsArrayBuffer(Blob blob) 61 | { 62 | JSReference.InvokeVoid("readAsArrayBuffer", blob.JSReference); 63 | } 64 | 65 | /// 66 | /// Starts a new read for some as a binarily encoded which can be read from once the load has ended which can be checked by setting the action . 67 | /// 68 | /// The that should be read asynchronously. 69 | /// 70 | public void ReadAsBinaryString(Blob blob) 71 | { 72 | JSReference.InvokeVoid("readAsBinaryString", blob.JSReference); 73 | } 74 | 75 | /// 76 | /// Starts a new read for some as a which can be read from once the load has ended which can be checked by setting the action . 77 | /// 78 | /// The that should be read asynchronously. 79 | /// An optional encoding for the text. The default is UTF-8. 80 | /// 81 | public void ReadAsText(Blob blob, string? encoding = null) 82 | { 83 | JSReference.InvokeVoid("readAsText", blob.JSReference, encoding); 84 | } 85 | 86 | /// 87 | /// Starts a new read for some as a base64 encoded Data URL which can be read from once the load has ended which can be checked by setting the action . 88 | /// 89 | /// The that should be read asynchronously. 90 | /// 91 | public void ReadAsDataURL(Blob blob) 92 | { 93 | JSReference.InvokeVoid("readAsDataURL", blob.JSReference); 94 | } 95 | 96 | /// 97 | /// Terminates the load if the is else it sets the result to . 98 | /// 99 | /// The read that should be terminated. 100 | /// 101 | public void Abort(Blob blob) 102 | { 103 | JSReference.InvokeVoid("abort", blob.JSReference); 104 | } 105 | 106 | /// 107 | /// Gets the state of the . 108 | /// 109 | /// As a standard either , or 110 | public ushort ReadyState => InProcessHelper.Invoke("getAttribute", JSReference, "readyState"); 111 | 112 | /// 113 | /// Checks whether the result is a either a or a byte array. 114 | /// 115 | /// Either the type of or type of []. 116 | public Type? ResultType => InProcessHelper.Invoke("isArrayBuffer", JSReference) ? typeof(byte[]) : typeof(string); 117 | 118 | /// 119 | /// Gets the result of the read a . 120 | /// 121 | /// A representing the read. If there was no result from the read or if the read has not ended yet then it will be . 122 | public string? ResultAsString => InProcessHelper.Invoke("getAttribute", JSReference, "result"); 123 | 124 | /// 125 | /// Gets the result of the read a []. 126 | /// 127 | /// A [] representing the read. If there was no result from the read or if the read has not ended yet then it will be . 128 | public byte[]? ResultAsByteArray => InProcessHelper.Invoke("arrayBuffer", InProcessHelper.Invoke("getAttribute", JSReference, "result")); 129 | 130 | /// 131 | /// Gets the error object reference which will be if no error occured. 132 | /// 133 | /// A nullable IJSObjectReference because it was out of scope to wrap the Exception API. 134 | public IJSObjectReference? Error => InProcessHelper.Invoke("getAttribute", JSReference, "error"); 135 | 136 | /// 137 | /// Invoked when a load starts. 138 | /// 139 | [Obsolete("This will be removed in the next major release in favor of AddOnLoadStartEventListener and RemoveOnLoadStartEventListener as they are more memory safe.")] 140 | [JsonIgnore] 141 | public new Action? OnLoadStart { get; set; } 142 | 143 | /// 144 | /// Invoked when the progress of a load changes which includes when it ends. 145 | /// 146 | [Obsolete("This will be removed in the next major release in favor of AddOnProgressEventListener and RemoveOnProgressEventListener as they are more memory safe.")] 147 | [JsonIgnore] 148 | public new Action? OnProgress { get; set; } 149 | 150 | /// 151 | /// Invoked when a load ends successfully. 152 | /// 153 | [Obsolete("This will be removed in the next major release in favor of AddOnLoadEventListener and RemoveOnLoadEventListener as they are more memory safe.")] 154 | [JsonIgnore] 155 | public new Action? OnLoad { get; set; } 156 | 157 | /// 158 | /// Invoked when a load is aborted. 159 | /// 160 | [Obsolete("This will be removed in the next major release in favor of AddOnAbortEventListener and RemoveOnAbortEventListener as they are more memory safe.")] 161 | [JsonIgnore] 162 | public new Action? OnAbort { get; set; } 163 | 164 | /// 165 | /// Invoked when a load fails due to an error. 166 | /// 167 | [Obsolete("This will be removed in the next major release in favor of AddOnErrorEventListener and RemoveOnErrorEventListener as they are more memory safe.")] 168 | [JsonIgnore] 169 | public new Action? OnError { get; set; } 170 | 171 | /// 172 | /// Invoked when a load finishes successfully or not. 173 | /// 174 | [Obsolete("This will be removed in the next major release in favor of AddOnLoadEndEventListener and RemoveOnLoadEndEventListener as they are more memory safe.")] 175 | [JsonIgnore] 176 | public new Action? OnLoadEnd { get; set; } 177 | 178 | /// Internal method. 179 | [Obsolete("This will be removed in the next major release.")] 180 | [JSInvokable] 181 | public void InvokeOnLoadStart(IJSInProcessObjectReference jsProgressEvent) 182 | { 183 | if (OnLoadStart is null) 184 | { 185 | return; 186 | } 187 | 188 | OnLoadStart.Invoke(new ProgressEventInProcess(JSRuntime, InProcessHelper, jsProgressEvent, new() { DisposesJSReference = true })); 189 | } 190 | 191 | /// Internal method. 192 | [Obsolete("This will be removed in the next major release.")] 193 | [JSInvokable] 194 | public void InvokeOnProgress(IJSInProcessObjectReference jsProgressEvent) 195 | { 196 | if (OnProgress is null) 197 | { 198 | return; 199 | } 200 | 201 | OnProgress.Invoke(new ProgressEventInProcess(JSRuntime, InProcessHelper, jsProgressEvent, new() { DisposesJSReference = true })); 202 | } 203 | 204 | /// Internal method. 205 | [Obsolete("This will be removed in the next major release.")] 206 | [JSInvokable] 207 | public void InvokeOnLoad(IJSInProcessObjectReference jsProgressEvent) 208 | { 209 | if (OnLoad is null) 210 | { 211 | return; 212 | } 213 | 214 | OnLoad.Invoke(new ProgressEventInProcess(JSRuntime, InProcessHelper, jsProgressEvent, new() { DisposesJSReference = true })); 215 | } 216 | 217 | /// Internal method. 218 | [Obsolete("This will be removed in the next major release.")] 219 | [JSInvokable] 220 | public void InvokeOnAbort(IJSInProcessObjectReference jsProgressEvent) 221 | { 222 | if (OnAbort is null) 223 | { 224 | return; 225 | } 226 | 227 | OnAbort.Invoke(new ProgressEventInProcess(JSRuntime, InProcessHelper, jsProgressEvent, new() { DisposesJSReference = true })); 228 | } 229 | 230 | /// Internal method. 231 | [Obsolete("This will be removed in the next major release.")] 232 | [JSInvokable] 233 | public void InvokeOnError(IJSInProcessObjectReference jsProgressEvent) 234 | { 235 | if (OnError is null) 236 | { 237 | return; 238 | } 239 | 240 | OnError.Invoke(new ProgressEventInProcess(JSRuntime, InProcessHelper, jsProgressEvent, new() { DisposesJSReference = true })); 241 | } 242 | 243 | /// Internal method. 244 | [Obsolete("This will be removed in the next major release.")] 245 | [JSInvokable] 246 | public void InvokeOnLoadEnd(IJSInProcessObjectReference jsProgressEvent) 247 | { 248 | if (OnLoadEnd is null) 249 | { 250 | return; 251 | } 252 | 253 | OnLoadEnd.Invoke(new ProgressEventInProcess(JSRuntime, InProcessHelper, jsProgressEvent, new() { DisposesJSReference = true })); 254 | } 255 | 256 | /// 257 | public void AddEventListener(string type, EventListenerInProcess? callback, AddEventListenerOptions? options = null) 258 | where TEvent : Event, IJSCreatable where TInProcessEvent : IJSInProcessCreatable 259 | { 260 | JSReference.InvokeVoid("addEventListener", type, callback?.JSReference, options); 261 | } 262 | 263 | /// 264 | public void AddEventListener(EventListenerInProcess? callback, AddEventListenerOptions? options = null) 265 | where TEvent : Event, IJSCreatable where TInProcessEvent : IJSInProcessCreatable 266 | { 267 | JSReference.InvokeVoid("addEventListener", typeof(TEvent).Name, callback?.JSReference, options); 268 | } 269 | 270 | /// 271 | public void RemoveEventListener(string type, EventListenerInProcess? callback, EventListenerOptions? options = null) 272 | where TEvent : Event, IJSCreatable where TInProcessEvent : IJSInProcessCreatable 273 | { 274 | JSReference.InvokeVoid("removeEventListener", type, callback?.JSReference, options); 275 | } 276 | 277 | /// 278 | public void RemoveEventListener(EventListenerInProcess? callback, EventListenerOptions? options = null) 279 | where TEvent : Event, IJSCreatable where TInProcessEvent : IJSInProcessCreatable 280 | { 281 | JSReference.InvokeVoid("removeEventListener", typeof(TEvent).Name, callback?.JSReference, options); 282 | } 283 | 284 | /// 285 | /// Adds an for when a load is started. 286 | /// 287 | /// Callback that will be invoked when the event is dispatched. 288 | /// 289 | public void AddOnLoadStartEventListener(EventListenerInProcess callback, AddEventListenerOptions? options = null) 290 | { 291 | AddEventListener("loadstart", callback, options); 292 | } 293 | 294 | /// 295 | /// Removes the event listener from the event listener list if it has been parsed to previously. 296 | /// 297 | /// The callback that you want to stop listening to events. 298 | /// 299 | public void RemoveOnLoadStartEventListener(EventListenerInProcess callback, EventListenerOptions? options = null) 300 | { 301 | RemoveEventListener("loadstart", callback, options); 302 | } 303 | 304 | /// 305 | /// Adds an for when the progress of a load changes which includes when it ends. 306 | /// 307 | /// Callback that will be invoked when the event is dispatched. 308 | /// 309 | public void AddOnProgressEventListener(EventListenerInProcess callback, AddEventListenerOptions? options = null) 310 | { 311 | AddEventListener("progress", callback, options); 312 | } 313 | 314 | /// 315 | /// Removes the event listener from the event listener list if it has been parsed to previously. 316 | /// 317 | /// The callback that you want to stop listening to events. 318 | /// 319 | public void RemoveOnProgressEventListener(EventListenerInProcess callback, EventListenerOptions? options = null) 320 | { 321 | RemoveEventListener("progress", callback, options); 322 | } 323 | 324 | /// 325 | /// Adds an for when a load ends successfully. 326 | /// 327 | /// Callback that will be invoked when the event is dispatched. 328 | /// 329 | public void AddOnLoadEventListener(EventListenerInProcess callback, AddEventListenerOptions? options = null) 330 | { 331 | AddEventListener("load", callback, options); 332 | } 333 | 334 | /// 335 | /// Removes the event listener from the event listener list if it has been parsed to previously. 336 | /// 337 | /// The callback that you want to stop listening to events. 338 | /// 339 | public void RemoveOnLoadEventListener(EventListenerInProcess callback, EventListenerOptions? options = null) 340 | { 341 | RemoveEventListener("load", callback, options); 342 | } 343 | 344 | /// 345 | /// Adds an for when a load is aborted. 346 | /// 347 | /// Callback that will be invoked when the event is dispatched. 348 | /// 349 | public void AddOnAbortEventListener(EventListenerInProcess callback, AddEventListenerOptions? options = null) 350 | { 351 | AddEventListener("abort", callback, options); 352 | } 353 | 354 | /// 355 | /// Removes the event listener from the event listener list if it has been parsed to previously. 356 | /// 357 | /// The callback that you want to stop listening to events. 358 | /// 359 | public void RemoveOnAbortEventListener(EventListenerInProcess callback, EventListenerOptions? options = null) 360 | { 361 | RemoveEventListener("abort", callback, options); 362 | } 363 | 364 | /// 365 | /// Adds an for when a load fails due to an error. 366 | /// 367 | /// Callback that will be invoked when the event is dispatched. 368 | /// 369 | public void AddOnErrorEventListener(EventListenerInProcess callback, AddEventListenerOptions? options = null) 370 | { 371 | AddEventListener("error", callback, options); 372 | } 373 | 374 | /// 375 | /// Removes the event listener from the event listener list if it has been parsed to previously. 376 | /// 377 | /// The callback that you want to stop listening to events. 378 | /// 379 | public void RemoveOnErrorEventListener(EventListenerInProcess callback, EventListenerOptions? options = null) 380 | { 381 | RemoveEventListener("error", callback, options); 382 | } 383 | 384 | /// 385 | /// Adds an for when a load finishes successfully or not. 386 | /// 387 | /// Callback that will be invoked when the event is dispatched. 388 | /// 389 | public void AddOnLoadEndEventListener(EventListenerInProcess callback, AddEventListenerOptions? options = null) 390 | { 391 | AddEventListener("loadend", callback, options); 392 | } 393 | 394 | /// 395 | /// Removes the event listener from the event listener list if it has been parsed to previously. 396 | /// 397 | /// The callback that you want to stop listening to events. 398 | /// 399 | public void RemoveOnLoadEndEventListener(EventListenerInProcess callback, EventListenerOptions? options = null) 400 | { 401 | RemoveEventListener("loadend", callback, options); 402 | } 403 | 404 | /// 405 | public bool DispatchEvent(Event eventInstance) 406 | { 407 | return IEventTargetInProcessExtensions.DispatchEvent(this, eventInstance); 408 | } 409 | 410 | /// 411 | public new async ValueTask DisposeAsync() 412 | { 413 | await InProcessHelper.DisposeAsync(); 414 | await base.DisposeAsync(); 415 | GC.SuppressFinalize(this); 416 | } 417 | } 418 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/FileReader.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.DOM; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | using System.Text.Json.Serialization; 5 | 6 | namespace KristofferStrube.Blazor.FileAPI; 7 | 8 | /// 9 | /// A reader that can asynchronously start reads of s or s and listen for events for its progress until it finishes. 10 | /// 11 | /// See the API definition here 12 | [IJSWrapperConverter] 13 | public class FileReader : EventTarget, IJSCreatable 14 | { 15 | /// 16 | /// A lazily loaded task that evaluates to a helper module instance from the Blazor.FileAPI library. 17 | /// 18 | protected readonly Lazy> fileApiHelperTask; 19 | 20 | /// 21 | public static new async Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 22 | { 23 | return await CreateAsync(jSRuntime, jSReference, new()); 24 | } 25 | 26 | /// 27 | public static new async Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) 28 | { 29 | IJSObjectReference helper = await jSRuntime.GetHelperAsync(); 30 | FileReader fileReader = new(jSRuntime, jSReference, options); 31 | await helper.InvokeVoidAsync("registerEventHandlersAsync", DotNetObjectReference.Create(fileReader), jSReference); 32 | return fileReader; 33 | } 34 | 35 | /// 36 | /// Constructs a wrapper instance using the standard constructor. 37 | /// 38 | /// An instance. 39 | /// A wrapper instance for a . 40 | public static new async Task CreateAsync(IJSRuntime jSRuntime) 41 | { 42 | IJSObjectReference helper = await jSRuntime.GetHelperAsync(); 43 | IJSObjectReference jSInstance = await helper.InvokeAsync("constructFileReader"); 44 | FileReader fileReader = new(jSRuntime, jSInstance, new() { DisposesJSReference = true }); 45 | await helper.InvokeVoidAsync("registerEventHandlersAsync", DotNetObjectReference.Create(fileReader), jSInstance); 46 | return fileReader; 47 | } 48 | 49 | /// 50 | protected FileReader(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) 51 | { 52 | fileApiHelperTask = new(jSRuntime.GetHelperAsync); 53 | } 54 | 55 | /// 56 | /// Starts a new read for some as an [] which can be read from once the load has ended which can be checked by setting the action . 57 | /// 58 | /// The that should be read asynchronously. 59 | /// 60 | public async Task ReadAsArrayBufferAsync(Blob blob) 61 | { 62 | await JSReference.InvokeVoidAsync("readAsArrayBuffer", blob.JSReference); 63 | } 64 | 65 | /// 66 | /// Starts a new read for some as a binarily encoded which can be read from once the load has ended which can be checked by setting the action . 67 | /// 68 | /// The that should be read asynchronously. 69 | /// 70 | public async Task ReadAsBinaryStringAsync(Blob blob) 71 | { 72 | await JSReference.InvokeVoidAsync("readAsBinaryString", blob.JSReference); 73 | } 74 | 75 | /// 76 | /// Starts a new read for some as a which can be read from once the load has ended which can be checked by setting the action . 77 | /// 78 | /// The that should be read asynchronously. 79 | /// An optional encoding for the text. The default is UTF-8. 80 | /// 81 | public async Task ReadAsTextAsync(Blob blob, string? encoding = null) 82 | { 83 | await JSReference.InvokeVoidAsync("readAsText", blob.JSReference, encoding); 84 | } 85 | 86 | /// 87 | /// Starts a new read for some as a base64 encoded Data URL which can be read from once the load has ended which can be checked by setting the action . 88 | /// 89 | /// The that should be read asynchronously. 90 | /// 91 | public async Task ReadAsDataURLAsync(Blob blob) 92 | { 93 | await JSReference.InvokeVoidAsync("readAsDataURL", blob.JSReference); 94 | } 95 | 96 | /// 97 | /// Terminates the load if the is else it sets the result to . 98 | /// 99 | /// The read that should be terminated. 100 | /// 101 | public async Task AbortAsync(Blob blob) 102 | { 103 | await JSReference.InvokeVoidAsync("abort", blob.JSReference); 104 | } 105 | 106 | /// 107 | /// The value returned by if the state of the is empty. 108 | /// 109 | public const ushort EMPTY = 0; 110 | 111 | /// 112 | /// The value returned by if the state of the is loading. 113 | /// 114 | public const ushort LOADING = 1; 115 | 116 | /// 117 | /// The value returned by if the state of the is done. 118 | /// 119 | public const ushort DONE = 2; 120 | 121 | /// 122 | /// Gets the state of the . 123 | /// 124 | /// As a standard either , or 125 | public async Task GetReadyStateAsync() 126 | { 127 | IJSObjectReference helper = await fileApiHelperTask.Value; 128 | return await helper.InvokeAsync("getAttribute", JSReference, "readyState"); 129 | } 130 | 131 | /// 132 | /// Checks whether the result is a either a or a byte array. 133 | /// 134 | /// Either the type of or type of []. 135 | public async Task GetResultTypeAsync() 136 | { 137 | IJSObjectReference helper = await fileApiHelperTask.Value; 138 | bool isArrayBuffer = await helper.InvokeAsync("isArrayBuffer", JSReference); 139 | return isArrayBuffer ? typeof(byte[]) : typeof(string); 140 | } 141 | 142 | /// 143 | /// Gets the result of the read a . 144 | /// 145 | /// A representing the read. If there was no result from the read or if the read has not ended yet then it will be . 146 | public async Task GetResultAsStringAsync() 147 | { 148 | IJSObjectReference helper = await fileApiHelperTask.Value; 149 | return await helper.InvokeAsync("getAttribute", JSReference, "result"); 150 | } 151 | 152 | /// 153 | /// Gets the result of the read a []. 154 | /// 155 | /// A [] representing the read. If there was no result from the read or if the read has not ended yet then it will be . 156 | public async Task GetResultAsByteArrayAsync() 157 | { 158 | IJSObjectReference helper = await fileApiHelperTask.Value; 159 | IJSObjectReference jSResult = await helper.InvokeAsync("getAttribute", JSReference, "result"); 160 | return await helper.InvokeAsync("arrayBuffer", jSResult); 161 | } 162 | 163 | /// 164 | /// Gets the error object reference which will be if no error occured. 165 | /// 166 | /// A nullable IJSObjectReference because it was out of scope to wrap the Exception API. 167 | // TODO: This should return actual error object from Blazor.WebIDL. 168 | public async Task GetErrorAsync() 169 | { 170 | IJSObjectReference helper = await fileApiHelperTask.Value; 171 | return await helper.InvokeAsync("getAttribute", JSReference, "error"); 172 | } 173 | 174 | /// 175 | /// Invoked when a load starts. 176 | /// 177 | [Obsolete("This will be removed in the next major release in favor of AddOnLoadStartEventListenerAsync and RemoveOnLoadStartEventListenerAsync as they are more memory safe.")] 178 | [JsonIgnore] 179 | public Func? OnLoadStart { get; set; } 180 | 181 | /// 182 | /// Invoked when the progress of a load changes which includes when it ends. 183 | /// 184 | [Obsolete("This will be removed in the next major release in favor of AddOnProgressEventListenerAsync and RemoveOnProgressEventListenerAsync as they are more memory safe.")] 185 | [JsonIgnore] 186 | public Func? OnProgress { get; set; } 187 | 188 | /// 189 | /// Invoked when a load ends successfully. 190 | /// 191 | [Obsolete("This will be removed in the next major release in favor of AddOnLoadEventListenerAsync and RemoveOnLoadEventListenerAsync as they are more memory safe.")] 192 | [JsonIgnore] 193 | public Func? OnLoad { get; set; } 194 | 195 | /// 196 | /// Invoked when a load is aborted. 197 | /// 198 | [Obsolete("This will be removed in the next major release in favor of AddOnAbortEventListenerAsync and RemoveOnAbortEventListenerAsync as they are more memory safe.")] 199 | [JsonIgnore] 200 | public Func? OnAbort { get; set; } 201 | 202 | /// 203 | /// Invoked when a load fails due to an error. 204 | /// 205 | [Obsolete("This will be removed in the next major release in favor of AddOnErrorEventListenerAsync and RemoveOnErrorEventListenerAsync as they are more memory safe.")] 206 | [JsonIgnore] 207 | public Func? OnError { get; set; } 208 | 209 | /// 210 | /// Invoked when a load finishes successfully or not. 211 | /// 212 | [Obsolete("This will be removed in the next major release in favor of AddOnLoadEndEventListenerAsync and RemoveOnLoadEndEventListenerAsync as they are more memory safe.")] 213 | [JsonIgnore] 214 | public Func? OnLoadEnd { get; set; } 215 | 216 | /// Internal method. 217 | [Obsolete("This will be removed in the next major release.")] 218 | [JSInvokable] 219 | public async Task InvokeOnLoadStartAsync(IJSObjectReference jsProgressEvent) 220 | { 221 | if (OnLoadStart is null) 222 | { 223 | return; 224 | } 225 | 226 | await OnLoadStart.Invoke(new ProgressEvent(JSRuntime, jsProgressEvent, new() { DisposesJSReference = true })); 227 | } 228 | 229 | /// Internal method. 230 | [Obsolete("This will be removed in the next major release.")] 231 | [JSInvokable] 232 | public async Task InvokeOnProgressAsync(IJSObjectReference jsProgressEvent) 233 | { 234 | if (OnProgress is null) 235 | { 236 | return; 237 | } 238 | 239 | await OnProgress.Invoke(new ProgressEvent(JSRuntime, jsProgressEvent, new() { DisposesJSReference = true })); 240 | } 241 | 242 | /// Internal method. 243 | [Obsolete("This will be removed in the next major release.")] 244 | [JSInvokable] 245 | public async Task InvokeOnLoadAsync(IJSObjectReference jsProgressEvent) 246 | { 247 | if (OnLoad is null) 248 | { 249 | return; 250 | } 251 | 252 | await OnLoad.Invoke(new ProgressEvent(JSRuntime, jsProgressEvent, new() { DisposesJSReference = true })); 253 | } 254 | 255 | /// Internal method. 256 | [Obsolete("This will be removed in the next major release.")] 257 | [JSInvokable] 258 | public async Task InvokeOnAbortAsync(IJSObjectReference jsProgressEvent) 259 | { 260 | if (OnAbort is null) 261 | { 262 | return; 263 | } 264 | 265 | await OnAbort.Invoke(new ProgressEvent(JSRuntime, jsProgressEvent, new() { DisposesJSReference = true })); 266 | } 267 | 268 | /// Internal method. 269 | [Obsolete("This will be removed in the next major release.")] 270 | [JSInvokable] 271 | public async Task InvokeOnErrorAsync(IJSObjectReference jsProgressEvent) 272 | { 273 | if (OnError is null) 274 | { 275 | return; 276 | } 277 | 278 | await OnError.Invoke(new ProgressEvent(JSRuntime, jsProgressEvent, new() { DisposesJSReference = true })); 279 | } 280 | 281 | /// Internal method. 282 | [Obsolete("This will be removed in the next major release.")] 283 | [JSInvokable] 284 | public async Task InvokeOnLoadEndAsync(IJSObjectReference jsProgressEvent) 285 | { 286 | if (OnLoadEnd is null) 287 | { 288 | return; 289 | } 290 | 291 | await OnLoadEnd.Invoke(new ProgressEvent(JSRuntime, jsProgressEvent, new() { DisposesJSReference = true })); 292 | } 293 | 294 | /// 295 | /// Adds an for when a load is started. 296 | /// 297 | /// Callback that will be invoked when the event is dispatched. 298 | /// 299 | public async Task AddOnLoadStartEventListenerAsync(EventListener callback, AddEventListenerOptions? options = null) 300 | { 301 | await AddEventListenerAsync("loadstart", callback, options); 302 | } 303 | 304 | /// 305 | /// Removes the event listener from the event listener list if it has been parsed to previously. 306 | /// 307 | /// The callback that you want to stop listening to events. 308 | /// 309 | public async Task RemoveOnLoadStartEventListenerAsync(EventListener callback, EventListenerOptions? options = null) 310 | { 311 | await RemoveEventListenerAsync("loadstart", callback, options); 312 | } 313 | 314 | /// 315 | /// Adds an for when the progress of a load changes which includes when it ends. 316 | /// 317 | /// Callback that will be invoked when the event is dispatched. 318 | /// 319 | public async Task AddOnProgressEventListenerAsync(EventListener callback, AddEventListenerOptions? options = null) 320 | { 321 | await AddEventListenerAsync("progress", callback, options); 322 | } 323 | 324 | /// 325 | /// Removes the event listener from the event listener list if it has been parsed to previously. 326 | /// 327 | /// The callback that you want to stop listening to events. 328 | /// 329 | public async Task RemoveOnProgressEventListenerAsync(EventListener callback, EventListenerOptions? options = null) 330 | { 331 | await RemoveEventListenerAsync("progress", callback, options); 332 | } 333 | 334 | /// 335 | /// Adds an for when a load ends successfully. 336 | /// 337 | /// Callback that will be invoked when the event is dispatched. 338 | /// 339 | public async Task AddOnLoadEventListenerAsync(EventListener callback, AddEventListenerOptions? options = null) 340 | { 341 | await AddEventListenerAsync("load", callback, options); 342 | } 343 | 344 | /// 345 | /// Removes the event listener from the event listener list if it has been parsed to previously. 346 | /// 347 | /// The callback that you want to stop listening to events. 348 | /// 349 | public async Task RemoveOnLoadEventListenerAsync(EventListener callback, EventListenerOptions? options = null) 350 | { 351 | await RemoveEventListenerAsync("load", callback, options); 352 | } 353 | 354 | /// 355 | /// Adds an for when a load is aborted. 356 | /// 357 | /// Callback that will be invoked when the event is dispatched. 358 | /// 359 | public async Task AddOnAbortEventListenerAsync(EventListener callback, AddEventListenerOptions? options = null) 360 | { 361 | await AddEventListenerAsync("abort", callback, options); 362 | } 363 | 364 | /// 365 | /// Removes the event listener from the event listener list if it has been parsed to previously. 366 | /// 367 | /// The callback that you want to stop listening to events. 368 | /// 369 | public async Task RemoveOnAbortEventListenerAsync(EventListener callback, EventListenerOptions? options = null) 370 | { 371 | await RemoveEventListenerAsync("abort", callback, options); 372 | } 373 | 374 | /// 375 | /// Adds an for when a load fails due to an error. 376 | /// 377 | /// Callback that will be invoked when the event is dispatched. 378 | /// 379 | public async Task AddOnErrorEventListenerAsync(EventListener callback, AddEventListenerOptions? options = null) 380 | { 381 | await AddEventListenerAsync("error", callback, options); 382 | } 383 | 384 | /// 385 | /// Removes the event listener from the event listener list if it has been parsed to previously. 386 | /// 387 | /// The callback that you want to stop listening to events. 388 | /// 389 | public async Task RemoveOnErrorEventListenerAsync(EventListener callback, EventListenerOptions? options = null) 390 | { 391 | await RemoveEventListenerAsync("error", callback, options); 392 | } 393 | 394 | /// 395 | /// Adds an for when a load finishes successfully or not. 396 | /// 397 | /// Callback that will be invoked when the event is dispatched. 398 | /// 399 | public async Task AddOnLoadEndEventListenerAsync(EventListener callback, AddEventListenerOptions? options = null) 400 | { 401 | await AddEventListenerAsync("loadend", callback, options); 402 | } 403 | 404 | /// 405 | /// Removes the event listener from the event listener list if it has been parsed to previously. 406 | /// 407 | /// The callback that you want to stop listening to events. 408 | /// 409 | public async Task RemoveOnLoadEndEventListenerAsync(EventListener callback, EventListenerOptions? options = null) 410 | { 411 | await RemoveEventListenerAsync("loadend", callback, options); 412 | } 413 | 414 | /// 415 | public new async ValueTask DisposeAsync() 416 | { 417 | if (fileApiHelperTask.IsValueCreated) 418 | { 419 | IJSObjectReference module = await helperTask.Value; 420 | await module.DisposeAsync(); 421 | } 422 | await base.DisposeAsync(); 423 | GC.SuppressFinalize(this); 424 | } 425 | } 426 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/IURLService.InProcess.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileAPI; 2 | 3 | /// 4 | public interface IURLServiceInProcess : IURLService 5 | { 6 | /// 7 | string CreateObjectURL(Blob obj); 8 | 9 | /// 10 | void RevokeObjectURL(string url); 11 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/IURLService.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileAPI; 2 | 3 | /// 4 | /// URL browser specs 5 | /// 6 | public interface IURLService 7 | { 8 | /// 9 | /// Creates a new Blob URL and adds that to the current contexts Blob URL store. 10 | /// 11 | /// The that you wish to create a URL for. 12 | /// a Blob Url which can be used as a source in different media like image, sound, iframe sources. 13 | Task CreateObjectURLAsync(Blob obj); 14 | 15 | /// 16 | /// Removes a specific URL from the current contexts Blob URL store. 17 | /// 18 | /// The URL that is to be removed. 19 | Task RevokeObjectURLAsync(string url); 20 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/KristofferStrube.Blazor.FileAPI.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net7.0;net8.0 5 | enable 6 | enable 7 | preview 8 | Blazor File API wrapper 9 | File API wrapper implementation for Blazor. 10 | KristofferStrube.Blazor.FileAPI 11 | Blazor;Wasm;Wrapper;FileAPI;File;Blob;FileReader;URL;FileSystem;JSInterop; 12 | https://github.com/KristofferStrube/Blazor.FileAPI 13 | git 14 | MIT 15 | 0.4.0 16 | Kristoffer Strube 17 | README.md 18 | icon.png 19 | true 20 | 21 | 22 | 23 | 24 | True 25 | \ 26 | 27 | 28 | True 29 | \ 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Options/BlobPart.cs: -------------------------------------------------------------------------------- 1 | namespace KristofferStrube.Blazor.FileAPI; 2 | 3 | 4 | /// 5 | /// Union Type representing either a [], a , or a . 6 | /// 7 | /// 8 | /// BlobPart browser specs 9 | /// 10 | public class BlobPart 11 | { 12 | internal readonly object Part; 13 | 14 | /// 15 | /// Creates a from a [] explicitly instead of using the implicit converter. 16 | /// 17 | /// A []. 18 | public BlobPart(byte[] part) 19 | { 20 | Part = part; 21 | } 22 | 23 | /// 24 | /// Creates a from a explicitly instead of using the implicit converter. 25 | /// 26 | /// A . 27 | public BlobPart(Blob part) 28 | { 29 | Part = part; 30 | } 31 | 32 | /// 33 | /// Creates a from a explicitly instead of using the implicit converter. 34 | /// 35 | /// A . 36 | public BlobPart(string part) 37 | { 38 | Part = part; 39 | } 40 | 41 | /// 42 | /// Creates a from a []. 43 | /// 44 | /// A []. 45 | public static implicit operator BlobPart(byte[] part) 46 | { 47 | return new(part); 48 | } 49 | 50 | /// 51 | /// Creates a from a . 52 | /// 53 | /// A . 54 | public static implicit operator BlobPart(Blob part) 55 | { 56 | return new(part); 57 | } 58 | 59 | /// 60 | /// Creates a from a . 61 | /// 62 | /// A . 63 | public static implicit operator BlobPart(string part) 64 | { 65 | return new(part); 66 | } 67 | } -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Options/BlobPropertyBag.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.FileAPI; 4 | 5 | /// 6 | /// BlobPropertyBag browser specs 7 | /// 8 | public class BlobPropertyBag 9 | { 10 | /// 11 | /// The MIME type of the new in lowercase. 12 | /// 13 | [JsonPropertyName("type")] 14 | public string Type { get; set; } = ""; 15 | 16 | /// 17 | /// The line endings for the new . 18 | /// 19 | [JsonPropertyName("endings")] 20 | public EndingType Endings { get; set; } = EndingType.Transparent; 21 | } 22 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/Options/FilePropertyBag.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace KristofferStrube.Blazor.FileAPI; 4 | 5 | /// 6 | /// FilePropertyBag browser specs 7 | /// 8 | public class FilePropertyBag : BlobPropertyBag 9 | { 10 | /// 11 | /// When the new was last modified. 12 | /// 13 | [JsonPropertyName("lastModified")] 14 | [JsonConverter(typeof(DateTimeConverter))] 15 | public DateTime LastModified { get; set; } = DateTime.UtcNow; 16 | } 17 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/ProgressEvent.InProcess.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.DOM; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.FileAPI; 6 | 7 | /// 8 | /// ProgressEvent browser specs 9 | /// 10 | public class ProgressEventInProcess : ProgressEvent, IJSInProcessCreatable 11 | { 12 | /// 13 | public new IJSInProcessObjectReference JSReference { get; } 14 | 15 | /// 16 | /// A helper module instance from the Blazor.FileAPI library. 17 | /// 18 | protected readonly IJSInProcessObjectReference InProcessHelper; 19 | 20 | /// 21 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference) 22 | { 23 | return await CreateAsync(jSRuntime, jSReference, new()); 24 | } 25 | 26 | /// 27 | public static async Task CreateAsync(IJSRuntime jSRuntime, IJSInProcessObjectReference jSReference, CreationOptions options) 28 | { 29 | IJSInProcessObjectReference InProcessHelper = await jSRuntime.GetInProcessHelperAsync(); 30 | return new ProgressEventInProcess(jSRuntime, InProcessHelper, jSReference, options); 31 | } 32 | 33 | /// 34 | protected internal ProgressEventInProcess(IJSRuntime jSRuntime, IJSInProcessObjectReference inProcessHelper, IJSInProcessObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) 35 | { 36 | JSReference = jSReference; 37 | InProcessHelper = inProcessHelper; 38 | } 39 | 40 | /// 41 | /// Indicates whether the total can be calculated. 42 | /// 43 | /// A indicating if the total length was computable. 44 | public bool LengthComputable => InProcessHelper.Invoke("getAttribute", JSReference, "lengthComputable"); 45 | 46 | /// 47 | /// The loaded number of bytes of the total. 48 | /// 49 | /// The length of the currently loaded part. 50 | public ulong Loaded => InProcessHelper.Invoke("getAttribute", JSReference, "loaded"); 51 | 52 | /// 53 | /// The total number of bytes if it was computable else this is 0. 54 | /// 55 | /// The total length of the read. 56 | public ulong Total => InProcessHelper.Invoke("getAttribute", JSReference, "total"); 57 | 58 | #region inherited from the the in-process event 59 | 60 | /// 61 | /// Returns the type of this 62 | /// 63 | public string Type => InProcessHelper.Invoke("getAttribute", JSReference, "type"); 64 | 65 | /// 66 | /// Gets the target of this . 67 | /// 68 | public new async Task GetTargetAsync() 69 | { 70 | IJSInProcessObjectReference? jSInstance = await InProcessHelper.InvokeAsync("getAttribute", JSReference, "target"); 71 | return jSInstance is null ? null : await EventTargetInProcess.CreateAsync(JSRuntime, jSInstance, new() { DisposesJSReference = true }); 72 | } 73 | 74 | /// 75 | /// Gets the current target of this . 76 | /// 77 | /// The object whose event listener’s callback is currently being invoked. 78 | public new async Task GetCurrentTargetAsync() 79 | { 80 | IJSInProcessObjectReference? jSInstance = await InProcessHelper.InvokeAsync("getAttribute", JSReference, "currentTarget"); 81 | return jSInstance is null ? null : await EventTargetInProcess.CreateAsync(JSRuntime, jSInstance, new() { DisposesJSReference = true }); 82 | } 83 | 84 | /// 85 | /// Returns the invocation target objects of event’s path (objects on which listeners will be invoked), except for any nodes in shadow trees of which the shadow root’s mode is "closed" that are not reachable from event’s currentTarget. 86 | /// 87 | /// An array of s 88 | public new async Task ComposedPathAsync() 89 | { 90 | IJSObjectReference jSArray = await JSReference.InvokeAsync("composedPath"); 91 | int length = await InProcessHelper.InvokeAsync("getAttribute", jSArray, "length"); 92 | return (await Task.WhenAll(Enumerable 93 | .Range(0, length) 94 | .Select(async i => await EventTargetInProcess.CreateAsync(JSRuntime, await InProcessHelper.InvokeAsync("getAttribute", jSArray, i))))) 95 | .ToArray(); 96 | } 97 | 98 | /// 99 | /// Returns the 's phase. 100 | /// 101 | public EventPhase EventPhase => InProcessHelper.Invoke("getAttribute", JSReference, "eventPhase"); 102 | 103 | /// 104 | /// When dispatched in a tree, invoking this method prevents the event from reaching any objects other than the current object. 105 | /// 106 | /// 107 | public void StopPropagation() 108 | { 109 | JSReference.InvokeVoid("stopPropagation"); 110 | } 111 | 112 | /// 113 | /// Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects. 114 | /// 115 | public void StopImmediatePropagation() 116 | { 117 | JSReference.InvokeVoid("stopImmediatePropagation"); 118 | } 119 | 120 | /// 121 | /// Returns if the event goes through its target’s ancestors in reverse tree order; otherwise . 122 | /// 123 | public bool Bubbles => InProcessHelper.Invoke("getAttribute", JSReference, "bubbles"); 124 | 125 | /// 126 | /// Its value does not always carry meaning, but can indicate that part of the operation during which event was dispatched,can be canceled by invoking the method. 127 | /// 128 | public bool Cancelable => InProcessHelper.Invoke("getAttribute", JSReference, "cancelable"); 129 | 130 | /// 131 | /// If invoked when the cancelable attribute value is , and while executing a listener for the event with passive set to , then it signals to the operation that caused event to be dispatched that it needs to be canceled. 132 | /// 133 | public void PreventDefault() 134 | { 135 | JSReference.InvokeVoid("preventDefault"); 136 | } 137 | 138 | /// 139 | /// Returns if was invoked successfully to indicate cancelation; otherwise . 140 | /// 141 | public bool DefaultPrevented => InProcessHelper.Invoke("getAttribute", JSReference, "defaultPrevented"); 142 | 143 | /// 144 | /// Returns if the event invokes listeners past a ShadowRoot node that is the root of its target; otherwise . 145 | /// 146 | public bool Composed => InProcessHelper.Invoke("getAttribute", JSReference, "composed"); 147 | 148 | /// 149 | /// Returns if the event was dispatched by the user agent, and otherwise. 150 | /// 151 | public bool IsTrusted => InProcessHelper.Invoke("getAttribute", JSReference, "isTrusted"); 152 | 153 | /// 154 | /// Returns the event’s timestamp as the number of milliseconds measured relative to the time origin. 155 | /// 156 | public double TimeStamp => InProcessHelper.Invoke("getAttribute", JSReference, "timeStamp"); 157 | 158 | #endregion 159 | 160 | /// 161 | public new async ValueTask DisposeAsync() 162 | { 163 | await InProcessHelper.DisposeAsync(); 164 | await base.DisposeAsync(); 165 | GC.SuppressFinalize(this); 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/ProgressEvent.cs: -------------------------------------------------------------------------------- 1 | using KristofferStrube.Blazor.DOM; 2 | using KristofferStrube.Blazor.WebIDL; 3 | using Microsoft.JSInterop; 4 | 5 | namespace KristofferStrube.Blazor.FileAPI; 6 | 7 | /// 8 | /// ProgressEvent browser specs 9 | /// 10 | public class ProgressEvent : Event, IJSCreatable 11 | { 12 | /// 13 | /// A lazily loaded task that evaluates to a helper module instance from the Blazor.FileAPI library. 14 | /// 15 | protected readonly Lazy> fileApiHelperTask; 16 | 17 | /// 18 | public static new async Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference) 19 | { 20 | return await CreateAsync(jSRuntime, jSReference, new()); 21 | } 22 | 23 | /// 24 | public static new Task CreateAsync(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) 25 | { 26 | return Task.FromResult(new ProgressEvent(jSRuntime, jSReference, options)); 27 | } 28 | 29 | /// 30 | protected internal ProgressEvent(IJSRuntime jSRuntime, IJSObjectReference jSReference, CreationOptions options) : base(jSRuntime, jSReference, options) 31 | { 32 | fileApiHelperTask = new(jSRuntime.GetHelperAsync); 33 | } 34 | 35 | /// 36 | /// Indicates whether the total can be calculated. 37 | /// 38 | /// A indicating if the total length was computable. 39 | public async Task GetLengthComputableAsync() 40 | { 41 | IJSObjectReference helper = await fileApiHelperTask.Value; 42 | return await helper.InvokeAsync("getAttribute", JSReference, "lengthComputable"); 43 | } 44 | 45 | /// 46 | /// The loaded number of bytes of the total. 47 | /// 48 | /// The length of the currently loaded part. 49 | public async Task GetLoadedAsync() 50 | { 51 | IJSObjectReference helper = await fileApiHelperTask.Value; 52 | return await helper.InvokeAsync("getAttribute", JSReference, "loaded"); 53 | } 54 | 55 | /// 56 | /// The total number of bytes if it was computable else this is 0. 57 | /// 58 | /// The total length of the read. 59 | public async Task GetTotalAsync() 60 | { 61 | IJSObjectReference helper = await fileApiHelperTask.Value; 62 | return await helper.InvokeAsync("getAttribute", JSReference, "total"); 63 | } 64 | 65 | /// 66 | public new async ValueTask DisposeAsync() 67 | { 68 | if (fileApiHelperTask.IsValueCreated) 69 | { 70 | IJSObjectReference module = await helperTask.Value; 71 | await module.DisposeAsync(); 72 | } 73 | await base.DisposeAsync(); 74 | GC.SuppressFinalize(this); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/URLService.InProcess.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileAPI; 4 | 5 | /// 6 | /// URL browser specs 7 | /// 8 | public class URLServiceInProcess : URLService, IURLServiceInProcess 9 | { 10 | /// 11 | protected new readonly IJSInProcessRuntime jSRuntime; 12 | 13 | /// 14 | /// Constructs a that can be used to access the partial part of the URL interface defined in the FileAPI definition. 15 | /// 16 | /// 17 | public URLServiceInProcess(IJSInProcessRuntime jSRuntime) : base(jSRuntime) 18 | { 19 | this.jSRuntime = jSRuntime; 20 | } 21 | 22 | /// 23 | /// Creates a new Blob URL and adds that to the current contexts Blob URL store. 24 | /// 25 | /// The that you wish to create a URL for. 26 | /// a Blob Url which can be used as a source in different media like image, sound, iframe sources. 27 | public string CreateObjectURL(Blob obj) 28 | { 29 | return jSRuntime.Invoke("URL.createObjectURL", obj.JSReference); 30 | } 31 | 32 | /// 33 | /// Removes a specific URL from the current contexts Blob URL store. 34 | /// 35 | /// The URL that is to be removed. 36 | public void RevokeObjectURL(string url) 37 | { 38 | jSRuntime.InvokeVoid("URL.revokeObjectURL", url); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/URLService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.JSInterop; 2 | 3 | namespace KristofferStrube.Blazor.FileAPI; 4 | 5 | /// 6 | public class URLService : IURLService 7 | { 8 | /// 9 | /// used for making calls in the . 10 | /// 11 | protected readonly IJSRuntime jSRuntime; 12 | 13 | /// 14 | /// Constructs a that can be used to access the partial part of the URL interface defined in the FileAPI definition. 15 | /// 16 | /// 17 | public URLService(IJSRuntime jSRuntime) 18 | { 19 | this.jSRuntime = jSRuntime; 20 | } 21 | 22 | /// 23 | public async Task CreateObjectURLAsync(Blob obj) 24 | { 25 | return await jSRuntime.InvokeAsync("URL.createObjectURL", obj.JSReference); 26 | } 27 | 28 | /// 29 | public async Task RevokeObjectURLAsync(string url) 30 | { 31 | await jSRuntime.InvokeVoidAsync("URL.revokeObjectURL", url); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using Microsoft.AspNetCore.Components.Web 2 | -------------------------------------------------------------------------------- /src/KristofferStrube.Blazor.FileAPI/wwwroot/KristofferStrube.Blazor.FileAPI.js: -------------------------------------------------------------------------------- 1 | export function getAttribute(object, attribute) { return object[attribute]; } 2 | 3 | export function arrayBuffer(buffer) { 4 | var bytes = new Uint8Array(buffer); 5 | return bytes; 6 | } 7 | 8 | export function constructBlob(blobParts, options) { 9 | return new Blob(blobParts, options); 10 | } 11 | 12 | export function constructFile(blobParts, fileName, options) { 13 | return new File(blobParts, fileName, options); 14 | } 15 | 16 | export function constructFileReader() { 17 | return new FileReader(); 18 | } 19 | 20 | export function registerEventHandlersAsync(objRef, jSInstance) { 21 | jSInstance.addEventListener('loadstart', (e) => objRef.invokeMethodAsync('InvokeOnLoadStartAsync', DotNet.createJSObjectReference(e))); 22 | jSInstance.addEventListener('progress', (e) => objRef.invokeMethodAsync('InvokeOnProgressAsync', DotNet.createJSObjectReference(e))); 23 | jSInstance.addEventListener('load', (e) => objRef.invokeMethodAsync('InvokeOnLoadAsync', DotNet.createJSObjectReference(e))); 24 | jSInstance.addEventListener('abort', (e) => objRef.invokeMethodAsync('InvokeOnAbortAsync', DotNet.createJSObjectReference(e))); 25 | jSInstance.addEventListener('error', (e) => objRef.invokeMethodAsync('InvokeOnErrorAsync', DotNet.createJSObjectReference(e))); 26 | jSInstance.addEventListener('loadend', (e) => objRef.invokeMethodAsync('InvokeOnLoadEndAsync', DotNet.createJSObjectReference(e))); 27 | } 28 | 29 | export function registerEventHandlers(objRef, jSInstance) { 30 | jSInstance.addEventListener('loadstart', (e) => objRef.invokeMethod('InvokeOnLoadStart', DotNet.createJSObjectReference(e))); 31 | jSInstance.addEventListener('progress', (e) => objRef.invokeMethod('InvokeOnProgress', DotNet.createJSObjectReference(e))); 32 | jSInstance.addEventListener('load', (e) => objRef.invokeMethod('InvokeOnLoad', DotNet.createJSObjectReference(e))); 33 | jSInstance.addEventListener('abort', (e) => objRef.invokeMethod('InvokeOnAbort', DotNet.createJSObjectReference(e))); 34 | jSInstance.addEventListener('error', (e) => objRef.invokeMethod('InvokeOnError', DotNet.createJSObjectReference(e))); 35 | jSInstance.addEventListener('loadend', (e) => objRef.invokeMethod('InvokeOnLoadEnd', DotNet.createJSObjectReference(e))); 36 | } 37 | 38 | export function isArrayBuffer(fileReader) { 39 | return (fileReader.result instanceof ArrayBuffer) 40 | } --------------------------------------------------------------------------------