Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Easily Render Flat Data in Blazor File Manager
Syncfusion, Inc. profile imageGayathri-github7
Gayathri-github7 forSyncfusion, Inc.

Posted on • Originally published atsyncfusion.com on

Easily Render Flat Data in Blazor File Manager

TL;DR: Discover how the Syncfusion Blazor File Manager simplifies file management. Learn to render flat data easily and handle file operations with code examples. Whether from local objects or cloud services, streamline your process and unlock Blazor File Manager’s potential!

The SyncfusionBlazor File Manager component is a graphical user interface that manages the file system. This component also provides easy navigation for browsing and selecting files and folders from the file system. Using this component, you can easily manage the file system and perform the most common file and folder operations like read, write, delete, create, rename, upload, edit, select, and sort.

From2024 Volume 1 onward, the Blazor File Manager includes support for rendering flat data objects.

Let’s see how to render flat data using the Blazor File Manager component with code examples.

What is flat data?

Flat data of local objects refers to a collection of files and folders stored with a defined structure. These objects can also be defined locally or retrieved from any file service provider injected from external services.

Why flat data?

Blazor File Manager can be populated from an injected service or local objects, eliminating the need for HTTP client requests and backend URL configuration. This allows you to utilize your required services, such as physical, Amazon, Azure, etc., through the File Manager’s actionevents. This supports all file operations like delete, cut, copy, paste, new folder creation, upload, download, etc.

Create a Blazor app with File Manager

  1. First, create a Blazor app by referring to thedocumentation.
  2. Then, render the File Manager within the Blazor app by following the steps provided on thegetting started page.

Add Blazor File Manager component

Now, add the Syncfusion Blazor File Manager component in the Razor file. Here, we’ll add the File Manager component to theIndex.razor file under the~/Pages folder.

Then, import theSyncfusion.Blazor.FileManager NuGet package.

Refer to the following code example.

@using Syncfusion.Blazor.FileManager<SfFileManagerTValue="FileManagerDirectoryContent"><FileManagerEventsTValue="FileManagerDirectoryContent"OnRead="OnReadAsync"></FileManagerEvents></SfFileManager>
Enter fullscreen modeExit fullscreen mode

Binding flat data with Blazor File Manager

List of objects

The Blazor File Manager provides the option to load a list of file or folder details withParentId mapping by assigning the response within the corresponding events. Initial data can be loaded through theOnRead event.

@code{List<FileManagerDirectoryContent>Data{get;set;}protectedoverridevoidOnInitialized(){Data=GetData();}privateasyncTaskOnReadAsync(ReadEventArgs<FileManagerDirectoryContent>args){stringpath=args.Path;List<FileManagerDirectoryContent>fileDetails=args.Folder;FileManagerResponse<FileManagerDirectoryContent>response=newFileManagerResponse<FileManagerDirectoryContent>();if(path=="/"){stringParentId=Data.Where(x=>string.IsNullOrEmpty(x.ParentId)).Select(x=>x.Id).First();response.CWD=Data.Where(x=>string.IsNullOrEmpty(x.ParentId)).First();response.Files=Data.Where(x=>x.ParentId==ParentId).ToList();}else{varchildItem=fileDetails.Count>0&&fileDetails[0]!=null?fileDetails[0]:Data.Where(x=>x.FilterPath==path).First();response.CWD=childItem;response.Files=Data.Where(x=>x.ParentId==childItem.Id).ToList();}awaitTask.Yield();args.Response=response;}privateList<FileManagerDirectoryContent>GetData(){List<FileManagerDirectoryContent>data=newList<FileManagerDirectoryContent>();data.Add(newFileManagerDirectoryContent(){CaseSensitive=false,DateCreated=newDateTime(2022,1,2),DateModified=newDateTime(2022,2,3),FilterPath="",FilterId="",HasChild=true,Id="0",IsFile=false,Name="Files",ParentId=null,ShowHiddenItems=false,Size=1779448,Type="folder"});data.Add(newFileManagerDirectoryContent(){CaseSensitive=false,DateCreated=newDateTime(2022,1,2),DateModified=newDateTime(2022,2,3),FilterId="0/",FilterPath="/",HasChild=false,Id="1",IsFile=false,Name="Documents",ParentId="0",ShowHiddenItems=false,Size=680786,Type="folder"});data.Add(newFileManagerDirectoryContent(){CaseSensitive=false,DateCreated=newDateTime(2022,1,2),DateModified=newDateTime(2022,2,3),FilterId="0/",FilterPath="/",HasChild=false,Id="2",IsFile=false,Name="Downloads",ParentId="0",ShowHiddenItems=false,Size=6172,Type="folder"});data.Add(newFileManagerDirectoryContent(){CaseSensitive=false,DateCreated=newDateTime(2022,1,2),DateModified=newDateTime(2022,2,3),FilterId="0/1/",FilterPath="/Documents/",HasChild=false,Id="5",IsFile=true,Name="EJ2 File Manager.docx",ParentId="1",ShowHiddenItems=false,Size=12403,Type=".docx"});}}
Enter fullscreen modeExit fullscreen mode

Injected service

Blazor File Manager can also be populated from an injected service, eliminating the need forFileManagerAjaxSettings URL configuration. This allows you to utilize your required services, such as physical, Amazon, Azure, etc., through the File Manager’s action events.

Theseevents enable you to access essential item details from the event argument. Subsequently, update the File Manager’s result data by incorporating the data returned from the injected service. Assign this returned data to theResponse property of the corresponding event argument.

To set up a locally injected physical service, create a new file with the extension.cs within the project. Then, include thisGitHub file service code and inject the created service into theprogram.cs file.

usingFlat_Data;usingFlat_Data.Data;usingSyncfusion.Blazor;...builder.Services.AddSyncfusionBlazor();builder.Services.AddSingleton<FileManagerService>();
Enter fullscreen modeExit fullscreen mode

Handling file operations

In the File Manager service, the details of the static folderwwwroot directory are fetched, and all file operations, such as reading, folder creation, renaming, getting images, cutting, copying, uploading, downloading, deleting, etc., are performed in the service end. The response is mapped to the File Manager through event actions.

Likewise, you can inject your own service with the required file operations and bind the response to the File Manager component. Here is an example of the list of file operations that can be handled through the service and action events.

Read

The initial set of files and folders can be retrieved from the required service and mapped to the File Manager through theOnRead event response.

publicasyncTaskOnReadAsync(ReadEventArgs<FileManagerDirectoryContent>args){args.Response=awaitFileManagerService.GetFiles(args.Path,false,args.Folder.ToArray());}
Enter fullscreen modeExit fullscreen mode

Folder creation

The new folder creation can be initiated from theFolderCreating event, which triggers before the folder is created.

publicasyncTaskFolderCreatingAsync(FolderCreateEventArgs<FileManagerDirectoryContent>args){args.Response=awaitFileManagerService.Create(args.Path,args.FolderName,args.ParentFolder);}
Enter fullscreen modeExit fullscreen mode

Delete

The file or folder deletion can be performed through theItemsDeleting event, which triggers before deleting an item.

publicasyncTaskItemsDeletingAsync(ItemsDeleteEventArgs<FileManagerDirectoryContent>args){string[]names=args.Files.Select(x=>x.Name).ToArray();args.Response=awaitFileManagerService.Delete(args.Path,names,args.Files.ToArray());}
Enter fullscreen modeExit fullscreen mode

Rename

The file or a folder can be renamed through theItemRenaming event, which triggers before renaming an item.

publicasyncTaskItemRenamingAsync(ItemRenameEventArgs<FileManagerDirectoryContent>args){args.Response=awaitFileManagerService.Rename(args.Path,args.File.Name,args.NewName,false,args.ShowFileExtension,args.File);}
Enter fullscreen modeExit fullscreen mode

Search

The search action can be performed through thesearching event.

publicasyncTaskSearchingAsync(SearchEventArgs<FileManagerDirectoryContent>args){args.Response=awaitFileManagerService.Search(args.Path,args.SearchText,false,false);}
Enter fullscreen modeExit fullscreen mode

Cut, copy, and paste

Moving actions like cut, copy, and paste can be performed through theItemsMoving event based on theIsCopy argument value.

publicasyncTaskItemsMovingAsync(ItemsMoveEventArgs<FileManagerDirectoryContent>args){string[]names=args.Files.Select(x=>x.Name).ToArray();if(args.IsCopy){args.Response=awaitFileManagerService.Copy(args.Path,args.TargetPath,names,args.TargetData,args.Files.ToArray());}else{args.Response=awaitFileManagerService.Move(args.Path,args.TargetPath,names,args.TargetData,args.Files.ToArray());}}
Enter fullscreen modeExit fullscreen mode

Upload

To perform an upload action in the File Manager component with injected service, utilize theItemsUploaded event. This event enables you to access details of the file selected in the browser, providing access to metadata such as the file name, size, and content type. To read the contents of the uploaded file, invoke theOpenReadStream() method of theIBrowserFile interface, which returns a stream for reading the file data.

@code{    public async Task ItemsUploadedAsync(ItemsUploadedEventArgs<FileManagerDirectoryContent> args)    {        string currentPath = args.Path;        try        {            foreach (var file in args.Files)            {                var folders = (file.FileInfo.Name).Split('/');                if (folders.Length > 1)                {                    for (var i = 0; i< folders.Length-1;i++){stringnewDirectoryPath =Path.Combine(FileManagerService.basePath+currentPath,folders[i]);if(Path.GetFullPath(newDirectoryPath)!=(Path.GetDirectoryName(newDirectoryPath)+Path.DirectorySeparatorChar+folders[i])){thrownewUnauthorizedAccessException("AccessdeniedforDirectory-traversal");}if(!Directory.Exists(newDirectoryPath)){awaitFileManagerService.Create(currentPath,folders[i]);}currentPath+=folders[i]+"/";}}varfullName =Path.Combine((FileManagerService.contentRootPath+currentPath),file.File.Name);using(varfilestream =newFileStream(fullName,FileMode.Create,FileAccess.Write)){awaitfile.File.OpenReadStream(long.MaxValue).CopyToAsync(filestream);}}}catch(Exceptionex){Console.WriteLine(ex.Message);}}}
Enter fullscreen modeExit fullscreen mode

Download

To perform a download action in the File Manager component with injected service, utilize theBeforeDownload event. This will allow you to retrieve the details of the downloaded item from the event argument. Updating the downloaded file’s stream data and name to theFileStream andDownloadFileName event arguments, respectively, completes the download action.

@code{    public void BeforeDownload(BeforeDownloadEventArgs<FileManagerDirectoryContent> args)    {        var downloadData = FileManagerService.Download(args.DownloadData.Path, args.DownloadData.Names, args.DownloadData.DownloadFileDetails.ToArray());        args.FileStream = downloadData.FileStream;        args.DownloadFileName = downloadData.FileDownloadName;    }}
Enter fullscreen modeExit fullscreen mode

Get image

To load an image in File Manager with an injected service, utilize theBeforeImageLoad event. This will allow you to retrieve the details of the downloaded item from the event argument. Updating the image file’s stream data to the event argumentFileStream completes the image retrieval operation.

@code{public async Task BeforeImageLoadAsync(BeforeImageLoadEventArgs<FileManagerDirectoryContent> args)    {        var result = await FileManagerService.GetImage(args.ImageUrl, false, args.FileDetails);        result.FileStream.Position = 0;        args.FileStream = result.FileStream;    }}
Enter fullscreen modeExit fullscreen mode

Get data from the cloud service

To get data from cloud services like Azure, Amazon, etc., we need to provide the credentials in the File Manager service constructor. Further, file operations can be handled similarly through component events.

For example, refer to the following code to performa read operation with theAmazon service.

@using Syncfusion.Blazor.FileManager@using InjectedAmazonService.Data@inject FileManagerAmazonService FileManagerAmazonService<SfFileManagerTValue="FileManagerDirectoryContent"><FileManagerEventsTValue="FileManagerDirectoryContent"OnRead="OnReadAsync"></FileManagerEvents></SfFileManager>@code{    public async Task OnReadAsync(ReadEventArgs<FileManagerDirectoryContent> args)    {        args.Response = await FileManagerAmazonService.GetFiles(args.Path, false, args.Folder.ToArray());    }}
Enter fullscreen modeExit fullscreen mode

FileManagerAmazonService

publicFileManagerAmazonService(){RegisterAmazonS3("bucket-name","<--awsAccessKeyId-->","<--awsSecretAccessKey-->","bucket-region");}// Register the Amazon client detailspublicvoidRegisterAmazonS3(stringname,stringawsAccessKeyId,stringawsSecretAccessKey,stringregion){bucketName=name;RegionEndpointbucketRegion=RegionEndpoint.GetBySystemName(region);client=newAmazonS3Client(awsAccessKeyId,awsSecretAccessKey,bucketRegion);GetBucketList();}publicasyncTask<FileManagerResponse<FileManagerDirectoryContent>>GetFiles(stringpath,boolshowHiddenItems,paramsFileManagerDirectoryContent[]data){FileManagerDirectoryContentcwd=newFileManagerDirectoryContent();List<FileManagerDirectoryContent>files=newList<FileManagerDirectoryContent>();List<FileManagerDirectoryContent>filesS3=newList<FileManagerDirectoryContent>();FileManagerResponse<FileManagerDirectoryContent>readResponse=newFileManagerResponse<FileManagerDirectoryContent>();awaitGetBucketList();try{if(path=="/")awaitListingObjectsAsync("/",RootName,false);elseawaitListingObjectsAsync("/",RootName.Replace("/","")+path,false);if(path=="/"){List<FileManagerDirectoryContent>s=newList<FileManagerDirectoryContent>();// Use a list instead of an arrayforeach(varyinresponse.S3Objects.Where(x=>x.Key==RootName))// Use foreach loop to iterate over the filtered S3Objects{s.Add(awaitCreateDirectoryContentInstanceAsync(y.Key.ToString().Replace("/",""),false,"Folder",y.Size,y.LastModified,y.LastModified,checkChild(y.Key),string.Empty));// Add the result of CreateDirectoryContentInstance to the list}if(s.Count>0)cwd=s[0];}else{cwd=awaitCreateDirectoryContentInstanceAsync(path.Split("/")[path.Split("/").Length-2],false,"Folder",0,DateTime.Now,DateTime.Now,Task.FromResult(response.CommonPrefixes.Count>0?true:false),path.Substring(0,path.IndexOf(path.Split("/")[path.Split("/").Length-2])));}}catch(Exceptionex){throwex;}try{if(response.CommonPrefixes.Count>0){foreach(varprefixinresponse.CommonPrefixes){varfile=awaitCreateDirectoryContentInstanceAsync(getFileName(prefix,path),false,"Folder",0,DateTime.Now,DateTime.Now,checkChild(prefix),getFilePath(prefix));files.Add(file);}}}catch(Exceptionex){throwex;}try{if(path=="/")ListingObjectsAsync("/",RootName,false).Wait();elseListingObjectsAsync("/",RootName.Replace("/","")+path,false).Wait();if(response.S3Objects.Count>0){foreach(varobjinresponse.S3Objects.Where(x=>x.Key!=RootName.Replace("/","")+path)){varfile=awaitCreateDirectoryContentInstanceAsync(obj.Key.ToString().Replace(RootName.Replace("/","")+path,"").Replace("/",""),true,Path.GetExtension(obj.Key.ToString()),obj.Size,obj.LastModified,obj.LastModified,checkChild(obj.Key),getFilterPath(obj.Key,path));filesS3.Add(file);}}}catch(Exceptionex){throwex;}if(filesS3.Count!=0)files=files.Union(filesS3).ToList();readResponse.CWD=cwd;try{if(cwd.Permission!=null&&!cwd.Permission.Read){readResponse.Files=null;accessMessage=cwd.Permission.Message;thrownewUnauthorizedAccessException("'"+cwd.Name+"' is not accessible. You need permission to perform the read action.");}}catch(Exceptione){ErrorDetailser=newErrorDetails();er.Message=e.Message.ToString();er.Code=er.Message.Contains("is not accessible. You need permission")?"401":"417";if(er.Code=="401"&&!string.IsNullOrEmpty(accessMessage)){er.Message=accessMessage;}readResponse.Error=er;awaitTask.Yield();returnawaitTask.FromResult(readResponse);}readResponse.Files=files;awaitTask.Yield();returnawaitTask.FromResult(readResponse);}privatestringgetFilePath(stringpathString){returnpathString.Substring(0,pathString.Length-pathString.Split("/")[pathString.Split("/").Length-2].Length-1).Substring(RootName.Length-1);}privatestringgetFileName(stringfileName,stringpath){returnfileName.Replace(RootName.Replace("/","")+path,"").Replace("/","");}privateasyncTask<FileManagerDirectoryContent>CreateDirectoryContentInstanceAsync(stringname,boolvalue,stringtype,longsize,DateTimecreateddate,DateTimemodifieddate,Task<bool>child,stringfilterpath){FileManagerDirectoryContenttempFile=newFileManagerDirectoryContent();tempFile.Name=name;tempFile.IsFile=value;tempFile.Type=type;tempFile.Size=size;tempFile.DateCreated=createddate;tempFile.DateModified=modifieddate;tempFile.HasChild=awaitchild;tempFile.FilterPath=filterpath;tempFile.Permission=GetPathPermission(filterpath+(value?name:Path.GetFileNameWithoutExtension(name)),value);returntempFile;}
Enter fullscreen modeExit fullscreen mode

References

For more details, refer to the Rendering Blazor File Manager with Flat Data project onGitHub andweb anddocumentation.

Conclusion

Thanks for reading! We hope you enjoyed this quick introduction to the rendering ofBlazor File Manager with flat data objects. This feature is available in the2024 Volume 1 release. Give it a try and provide your valuable feedback.

Check out ourRelease Notes andWhat’s New pages to see other controls and features available with this release.

The new version is available on theLicense and Downloads page for existing Syncfusion customers. If you’re not yet our customer, you can sign up for a30-day free trial to evaluate these features.

For questions, you can reach us through oursupport forums,support portal, orfeedback portal.

Related blogs

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Syncfusion provides third-party UI components for React, Vue, Angular, JavaScript, Blazor, .NET MAUI, ASP.NET MVC, Core, WinForms, WPF, UWP and Xamarin.

More fromSyncfusion, Inc.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp