Saturday, May 18, 2024
HomeC#Simply Render Flat Information in Blazor File Supervisor

Simply Render Flat Information in Blazor File Supervisor


TL;DR: Uncover how the Syncfusion Blazor File Supervisor simplifies file administration. Be taught to render flat information simply and deal with file operations with code examples. Whether or not from native objects or cloud companies, streamline your course of and unlock Blazor File Supervisor’s potential!

The Syncfusion Blazor File Supervisor part is a graphical person interface that manages the file system. This part additionally supplies straightforward navigation for shopping and deciding on recordsdata and folders from the file system. Utilizing this part, you may simply handle the file system and carry out the commonest file and folder operations like learn, write, delete, create, rename, add, edit, choose, and type.

From 2024 Quantity 1 onward, the Blazor File Supervisor contains assist for rendering flat information objects.

Let’s see the right way to render flat information utilizing the Blazor File Supervisor part with code examples.

What’s flat information?

Flat information of native objects refers to a group of recordsdata and folders saved with an outlined construction. These objects may also be outlined domestically or retrieved from any file service supplier injected from exterior companies.

Why flat information?

Blazor File Supervisor could be populated from an injected service or native objects, eliminating the necessity for HTTP shopper requests and backend URL configuration. This lets you make the most of your required companies, similar to bodily, Amazon, Azure, and so forth., by the File Supervisor’s motion occasions. This helps all file operations like delete, minimize, copy, paste, new folder creation, add, obtain, and so forth.

Create a Blazor app with File Supervisor

  1. First, create a Blazor app by referring to the documentation.
  2. Then, render the File Supervisor inside the Blazor app by following the steps offered on the getting began web page.

Add Blazor File Supervisor part

Now, add the Syncfusion Blazor File Supervisor part within the Razor file. Right here, we’ll add the File Supervisor part to the Index.razor file below the ~/Pages folder.

Then, import the Syncfusion.Blazor.FileManager NuGet package deal.

Consult with the next code instance.

@utilizing Syncfusion.Blazor.FileManager

<SfFileManager TValue="FileManagerDirectoryContent">
 <FileManagerEvents TValue="FileManagerDirectoryContent" OnRead="OnReadAsync"></FileManagerEvents>
</SfFileManager>

Binding flat information with Blazor File Supervisor

Record of objects

The Blazor File Supervisor supplies the choice to load a listing of file or folder particulars with ParentId mapping by assigning the response inside the corresponding occasions. Preliminary information could be loaded by the OnRead occasion.

@code
{
    Record<FileManagerDirectoryContent> Information { get; set; }

    protected override void OnInitialized()
    {
        Information = GetData();
    }
    personal async Job OnReadAsync(ReadEventArgs<FileManagerDirectoryContent> args)
    {
        string path = args.Path;
        Record<FileManagerDirectoryContent> fileDetails = args.Folder;
        FileManagerResponse<FileManagerDirectoryContent> response = new FileManagerResponse<FileManagerDirectoryContent>();
        if (path == "/")
        {
            string ParentId = Information
                .The place(x => string.IsNullOrEmpty(x.ParentId))
                .Choose(x => x.Id).First();
            response.CWD = Information
                .The place(x => string.IsNullOrEmpty(x.ParentId)).First();
            response.Recordsdata = Information
                .The place(x => x.ParentId == ParentId).ToList();
        }
        else
        {
            var childItem = fileDetails.Depend > 0 && fileDetails[0] != null ? fileDetails[0] : Information
                .The place(x => x.FilterPath == path).First();
            response.CWD = childItem;
            response.Recordsdata = Information
                .The place(x => x.ParentId == childItem.Id).ToList();
        }
        await Job.Yield();
        args.Response = response;
    }

    personal Record<FileManagerDirectoryContent> GetData()
    {
        Record<FileManagerDirectoryContent> information = new Record<FileManagerDirectoryContent>();
        information.Add(new FileManagerDirectoryContent()
        {
            CaseSensitive = false,
            DateCreated = new DateTime(2022, 1, 2),
            DateModified = new DateTime(2022, 2, 3),
            FilterPath = "",
            FilterId = "",
            HasChild = true,
            Id = "0",
            IsFile = false,
            Identify = "Recordsdata",
            ParentId = null,
            ShowHiddenItems = false,
            Measurement = 1779448,
            Kind = "folder"
        });
        information.Add(new FileManagerDirectoryContent()
        {
            CaseSensitive = false,
            DateCreated = new DateTime(2022, 1, 2),
            DateModified = new DateTime(2022, 2, 3),
            FilterId = "0/",
            FilterPath = "/",
            HasChild = false,
            Id = "1",
            IsFile = false,
            Identify = "Paperwork",
            ParentId = "0",
            ShowHiddenItems = false,
            Measurement = 680786,
            Kind = "folder"
        });
        information.Add(new FileManagerDirectoryContent()
        {
            CaseSensitive = false,
            DateCreated = new DateTime(2022, 1, 2),
            DateModified = new DateTime(2022, 2, 3),
            FilterId = "0/",
            FilterPath = "/",
            HasChild = false,
            Id = "2",
            IsFile = false,
            Identify = "Downloads",
            ParentId = "0",
            ShowHiddenItems = false,
            Measurement = 6172,
            Kind = "folder"
        });
        information.Add(new FileManagerDirectoryContent()
        {
            CaseSensitive = false,
            DateCreated = new DateTime(2022, 1, 2),
            DateModified = new DateTime(2022, 2, 3),
            FilterId = "0/1/",
            FilterPath = "/Paperwork/",
            HasChild = false,
            Id = "5",
            IsFile = true,
            Identify = "EJ2 File Supervisor.docx",
            ParentId = "1",
            ShowHiddenItems = false,
            Measurement = 12403,
            Kind = ".docx"
        });
       
    }
}

Injected service

Blazor File Supervisor may also be populated from an injected service, eliminating the necessity for FileManagerAjaxSettings URL configuration. This lets you make the most of your required companies, similar to bodily, Amazon, Azure, and so forth., by the File Supervisor’s motion occasions.

These occasions allow you to entry important merchandise particulars from the occasion argument. Subsequently, replace the File Supervisor’s end result information by incorporating the information returned from the injected service. Assign this returned information to the Response property of the corresponding occasion argument.

To arrange a domestically injected bodily service, create a brand new file with the extension .cs inside the challenge. Then, embody this GitHub file service code and inject the created service into the program.cs file.

utilizing Flat_Data;
utilizing Flat_Data.Information;
utilizing Syncfusion.Blazor;
 
...
builder.Companies.AddSyncfusionBlazor();
builder.Companies.AddSingleton<FileManagerService>();

Dealing with file operations

Within the File Supervisor service, the small print of the static folder wwwroot listing are fetched, and all file operations, similar to studying, folder creation, renaming, getting photographs, reducing, copying, importing, downloading, deleting, and so forth., are carried out within the service finish. The response is mapped to the File Supervisor by occasion actions. 

Likewise, you may inject your individual service with the required file operations and bind the response to the File Supervisor part. Right here is an instance of the record of file operations that may be dealt with by the service and motion occasions.

Learn

The preliminary set of recordsdata and folders could be retrieved from the required service and mapped to the File Supervisor by the OnRead occasion response.

public async Job OnReadAsync(ReadEventArgs<FileManagerDirectoryContent> args)
{
    args.Response = await FileManagerService.GetFiles(args.Path, false, args.Folder.ToArray());
}

Folder creation

The brand new folder creation could be initiated from the FolderCreating occasion, which triggers earlier than the folder is created.

public async Job FolderCreatingAsync(FolderCreateEventArgs<FileManagerDirectoryContent> args)
{
        args.Response = await FileManagerService.Create(args.Path, args.FolderName,args.ParentFolder);
}

Delete

The file or folder deletion could be carried out by the ItemsDeleting occasion, which triggers earlier than deleting an merchandise.

public async Job ItemsDeletingAsync(ItemsDeleteEventArgs<FileManagerDirectoryContent> args)
{
     string[] names = args.Recordsdata.Choose(x => x.Identify).ToArray();
     args.Response = await FileManagerService.Delete(args.Path, names, args.Recordsdata.ToArray());
}

Rename

The file or a folder could be renamed by the ItemRenaming occasion, which triggers earlier than renaming an merchandise.

public async Job ItemRenamingAsync(ItemRenameEventArgs<FileManagerDirectoryContent> args)
{
        args.Response = await FileManagerService.Rename(args.Path, args.File.Identify, args.NewName, false, args.ShowFileExtension, args.File);
}

Search

The search motion could be carried out by the looking out occasion.

public async Job SearchingAsync(SearchEventArgs<FileManagerDirectoryContent> args)
{
    args.Response = await FileManagerService.Search(args.Path, args.SearchText, false, false);
}

Minimize, copy, and paste

Shifting actions like minimize, copy, and paste could be carried out by the ItemsMoving occasion primarily based on the IsCopy argument worth.

public async Job ItemsMovingAsync(ItemsMoveEventArgs<FileManagerDirectoryContent> args)
{
     string[] names = args.Recordsdata.Choose(x => x.Identify).ToArray();
     if (args.IsCopy)
     {
         args.Response = await FileManagerService.Copy(args.Path, args.TargetPath, names, args.TargetData, args.Recordsdata.ToArray());
     }
     else
     {
         args.Response = await FileManagerService.Transfer(args.Path, args.TargetPath, names, args.TargetData, args.Recordsdata.ToArray());
     }
}

Add

To carry out an add motion within the File Supervisor part with injected service, make the most of the ItemsUploaded occasion. This occasion allows you to entry particulars of the file chosen within the browser, offering entry to metadata such because the file title, measurement, and content material sort. To learn the contents of the uploaded file, invoke the OpenReadStream() technique of the IBrowserFile interface, which returns a stream for studying the file information.

@code{

    public async Job ItemsUploadedAsync(ItemsUploadedEventArgs<FileManagerDirectoryContent> args)
    {
        string currentPath = args.Path;
        attempt
        {
            foreach (var file in args.Recordsdata)
            {
                var folders = (file.FileInfo.Identify).Cut up('/');
                if (folders.Size > 1)
                {
                    for (var i = 0; i < folders.Size - 1; i++)
                    {
                        string newDirectoryPath = Path.Mix(FileManagerService.basePath + currentPath, folders[i]);
                        if (Path.GetFullPath(newDirectoryPath) != (Path.GetDirectoryName(newDirectoryPath) + Path.DirectorySeparatorChar + folders[i]))
                        {
                            throw new UnauthorizedAccessException("Entry denied for Listing-traversal");
                        }
                        if (!Listing.Exists(newDirectoryPath))
                        {
                            await FileManagerService.Create(currentPath, folders[i]);
                        }
                        currentPath += folders[i] + "/";
                    }
                }
                var fullName = Path.Mix((FileManagerService.contentRootPath + currentPath), file.File.Identify);
                utilizing (var filestream = new FileStream(fullName, FileMode.Create, FileAccess.Write))
                {
                    await file.File.OpenReadStream(lengthy.MaxValue).CopyToAsync(filestream);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Obtain

To carry out a obtain motion within the File Supervisor part with injected service, make the most of the BeforeDownload occasion. It will permit you to retrieve the small print of the downloaded merchandise from the occasion argument. Updating the downloaded file’s stream information and title to the FileStream and DownloadFileName occasion arguments, respectively, completes the obtain motion.

@code{

    public void BeforeDownload(BeforeDownloadEventArgs<FileManagerDirectoryContent> args)
    {
        var downloadData = FileManagerService.Obtain(args.DownloadData.Path, args.DownloadData.Names, args.DownloadData.DownloadFileDetails.ToArray());
        args.FileStream = downloadData.FileStream;
        args.DownloadFileName = downloadData.FileDownloadName;
    }
}

Get picture

To load a picture in File Supervisor with an injected service, make the most of the BeforeImageLoad occasion. It will permit you to retrieve the small print of the downloaded merchandise from the occasion argument. Updating the picture file’s stream information to the occasion argument FileStream completes the picture retrieval operation.

@code{

public async Job BeforeImageLoadAsync(BeforeImageLoadEventArgs<FileManagerDirectoryContent> args)
    {
        var end result = await FileManagerService.GetImage(args.ImageUrl, false, args.FileDetails);
        end result.FileStream.Place = 0;
        args.FileStream = end result.FileStream;
    }
}

Get information from the cloud service

To get information from cloud companies like Azure, Amazon, and so forth., we have to present the credentials within the File Supervisor service constructor. Additional, file operations could be dealt with equally by part occasions.

For instance, check with the next code to carry out a learn operation with the Amazon service.

@utilizing Syncfusion.Blazor.FileManager
@utilizing InjectedAmazonService.Information
@inject FileManagerAmazonService FileManagerAmazonService
<SfFileManager TValue="FileManagerDirectoryContent">
    <FileManagerEvents TValue="FileManagerDirectoryContent" OnRead="OnReadAsync"></FileManagerEvents>
</SfFileManager>
@code
{
    public async Job OnReadAsync(ReadEventArgs<FileManagerDirectoryContent> args)
    {
        args.Response = await FileManagerAmazonService.GetFiles(args.Path, false, args.Folder.ToArray());
    }
}

FileManagerAmazonService

public FileManagerAmazonService()
{
     RegisterAmazonS3("bucket-name", "<--awsAccessKeyId-->", "<--awsSecretAccessKey-->", "bucket-region");
 
}// Register the Amazon shopper particulars
public void RegisterAmazonS3(string title, string awsAccessKeyId, string awsSecretAccessKey, string area)
{
     bucketName = title;
     RegionEndpoint bucketRegion = RegionEndpoint.GetBySystemName(area);
     shopper = new AmazonS3Client(awsAccessKeyId, awsSecretAccessKey, bucketRegion);
     GetBucketList();
}

public async Job<FileManagerResponse<FileManagerDirectoryContent>> GetFiles(string path, bool showHiddenItems, params FileManagerDirectoryContent[] information)
{
    FileManagerDirectoryContent cwd = new FileManagerDirectoryContent();
    Record<FileManagerDirectoryContent> recordsdata = new Record<FileManagerDirectoryContent>();
    Record<FileManagerDirectoryContent> filesS3 = new Record<FileManagerDirectoryContent>();
    FileManagerResponse<FileManagerDirectoryContent> readResponse = new FileManagerResponse<FileManagerDirectoryContent>();
    await GetBucketList();
    attempt
    {
        if (path == "/") await ListingObjectsAsync("/", RootName, false); else await ListingObjectsAsync("/", RootName.Substitute("/", "") + path, false);
        if (path == "/")
        {
            Record<FileManagerDirectoryContent> s = new Record<FileManagerDirectoryContent>(); // Use a listing as a substitute of an array
            foreach (var y in response.S3Objects.The place(x => x.Key == RootName)) // Use foreach loop to iterate over the filtered S3Objects
            {
                s.Add(await CreateDirectoryContentInstanceAsync(y.Key.ToString().Substitute("/", ""), false, "Folder", y.Measurement, y.LastModified, y.LastModified, checkChild(y.Key), string.Empty)); // Add the results of CreateDirectoryContentInstance to the record
            }
            if (s.Depend > 0) cwd = s[0];
        }
        else
        {
            cwd = await CreateDirectoryContentInstanceAsync(path.Cut up("/")[path.Split("/").Length - 2], false, "Folder", 0, DateTime.Now, DateTime.Now, Job.FromResult(response.CommonPrefixes.Depend > 0 ? true : false), path.Substring(0, path.IndexOf(path.Cut up("/")[path.Split("/").Length - 2])));
        }
    }
    catch (Exception ex) { throw ex; }
    attempt
    {
        if (response.CommonPrefixes.Depend > 0)
        {
            foreach (var prefix in response.CommonPrefixes)
            {
                var file = await CreateDirectoryContentInstanceAsync(getFileName(prefix, path), false, "Folder", 0, DateTime.Now, DateTime.Now, checkChild(prefix), getFilePath(prefix));
                recordsdata.Add(file);
            }
        }
    }
    catch (Exception ex) { throw ex; }
    attempt
    {
        if (path == "/") ListingObjectsAsync("/", RootName, false).Wait(); else ListingObjectsAsync("/", RootName.Substitute("/", "") + path, false).Wait();
        if (response.S3Objects.Depend > 0)
        {
            foreach (var obj in response.S3Objects.The place(x => x.Key != RootName.Substitute("/", "") + path))
            {
                var file = await CreateDirectoryContentInstanceAsync(obj.Key.ToString().Substitute(RootName.Substitute("/", "") + path, "").Substitute("/", ""), true, Path.GetExtension(obj.Key.ToString()), obj.Measurement, obj.LastModified, obj.LastModified, checkChild(obj.Key), getFilterPath(obj.Key, path));
                filesS3.Add(file);
            }
        }
    }
    catch (Exception ex) { throw ex; }
    if (filesS3.Depend != 0) recordsdata = recordsdata.Union(filesS3).ToList();
    readResponse.CWD = cwd;
    attempt
    {
        if (cwd.Permission != null && !cwd.Permission.Learn)
        {
            readResponse.Recordsdata = null;
            accessMessage = cwd.Permission.Message;
            throw new UnauthorizedAccessException("'" + cwd.Identify + "' just isn't accessible. You want permission to carry out the learn motion.");
        }
    }
    catch (Exception e)
    {
        ErrorDetails er = new ErrorDetails();
        er.Message = e.Message.ToString();
        er.Code = er.Message.Accommodates("just isn't accessible. You want permission") ? "401" : "417";
        if (er.Code == "401" && !string.IsNullOrEmpty(accessMessage)) { er.Message = accessMessage; }
        readResponse.Error = er;
        await Job.Yield();
        return await Job.FromResult(readResponse);
    }
    readResponse.Recordsdata = recordsdata;
    await Job.Yield();
    return await Job.FromResult(readResponse);
}
 
personal string getFilePath(string pathString)
{
    return pathString.Substring(0, pathString.Size - pathString.Cut up("/")[pathString.Split("/").Length - 2].Size - 1).Substring(RootName.Size - 1);
}
 
personal string getFileName(string fileName, string path)
{
    return fileName.Substitute(RootName.Substitute("/", "") + path, "").Substitute("/", "");
}
 
personal async Job<FileManagerDirectoryContent> CreateDirectoryContentInstanceAsync(string title, bool worth, string sort, lengthy measurement, DateTime createddate, DateTime modifieddate, Job<bool> baby, string filterpath)
{
    FileManagerDirectoryContent tempFile = new FileManagerDirectoryContent();
    tempFile.Identify = title;
    tempFile.IsFile = worth;
    tempFile.Kind = sort;
    tempFile.Measurement = measurement;
    tempFile.DateCreated = createddate;
    tempFile.DateModified = modifieddate;
    tempFile.HasChild = await baby;
    tempFile.FilterPath = filterpath;
    tempFile.Permission = GetPathPermission(filterpath + (worth ? title : Path.GetFileNameWithoutExtension(title)), worth);
    return tempFile;
}

References

For extra particulars, check with the Rendering Blazor File Supervisor with Flat Information challenge on GitHub and internet and documentation.

Conclusion

Thanks for studying! We hope you loved this fast introduction to the rendering of Blazor File Supervisor with flat information objects. This function is obtainable within the 2024 Quantity 1 launch. Give it a attempt to present your helpful suggestions.

Take a look at our Launch Notes and What’s New pages to see different controls and options obtainable with this launch.

The brand new model is obtainable on the License and Downloads web page for current Syncfusion prospects. In the event you’re not but our buyer, you may join a 30-day free trial to guage these options.

For questions, you may attain us by our assist boards, assist portal, or suggestions portal.

Associated blogs

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments