用于浏览器API文件系统访问的外汇包装器
API使得可以从浏览器文件和目录中读取并写入您的本地文件系统。
免责声明:API在有限的浏览器集中支持。 Firefox,Android和iOS移动浏览器最明显的支持。
可以通过https://kristofferstrube.github.io/blazor.filesystemstemaccess/对示例项目进行演示。
在每个页面上,您可以在右上角找到该示例的相应代码。
在主页上,您可以查看API在使用的浏览器中是否至少具有最小的支持。
在状态页面上,您可以看到该包装器涵盖了多少WebIdl规格。
您需要安装.NET 7.0或更新以使用库。
下载.NET 7
您可以在IDE中使用Nuget安装包裹,或使用命令行中的软件包管理器:
dotnet add package KristofferStrube.Blazor.FileSystemAccess该软件包可用于Blazor WebAssembly和Blazor Server Projects。 (请注意,由于带宽问题,Blazor Server不支持大文件的流传输。)
您还需要引用包装以在页面中使用它。可以通过添加以下内容来在_Import.razor中完成。
@ using KristofferStrube . Blazor . FileSystemAccess 使服务在所有页面中可用的一种简单方法是将其注册在IServiceCollection中,以便可以在需要它的页面中注入依赖项。这是在Program.cs中完成的,通过在构建主机并运行主机之前添加以下内容。
var builder = WebAssemblyHostBuilder . CreateDefault ( args ) ;
builder . RootComponents . Add < App > ( "#app" ) ;
builder . RootComponents . Add < HeadOutlet > ( "head::after" ) ;
// Other services are added.
builder . Services . AddFileSystemAccessService ( ) ;
await builder . Build ( ) . RunAsync ( ) ; 然后,可以将服务注入类似的页面:
@inject IFileSystemAccessService FileSystemAccessService ;然后,您可以使用IFileSystemAccessService打开FileSystemAccess API中可用的三个对话框之一:
< button @onclick = " OpenAndReadFile " >Open File Picker for Single File and Read</ button >
< br />
@Text
@code {
private string Text = " " ;
private async Task OpenAndReadFile ()
{
FileSystemFileHandle ? fileHandle = null ;
try
{
OpenFilePickerOptionsStartInWellKnownDirectory options = new ()
{
Multiple = false ,
StartIn = WellKnownDirectory . Downloads
};
var fileHandles = await FileSystemAccessService . ShowOpenFilePickerAsync ( options );
fileHandle = fileHandles . Single ();
}
catch ( JSException ex )
{
// Handle Exception or cancelation of File Access prompt
Console . WriteLine ( ex );
}
finally
{
if ( fileHandle is not null )
{
var file = await fileHandle . GetFileAsync ();
Text = await file . TextAsync ();
StateHasChanged ();
}
}
}
}如果您发现包裹有任何错误或对功能有希望,请随时在存储库上打开问题。
一个已知的问题是,不支持使用流在Blazor服务器中流式传输大量数据。
该项目使用Blazor.FileSystem软件包返回FileSystemHandle s均为FileSystemFileHande s and FileSystemDirectoryHandle s。
该存储库是具有灵感的构建,并在以下一系列文章中提供了帮助: