Setting the root folder dynamically

Hi,

I am using the FileManager component and I would like to set the FileManager root folder to a custom name based on client name or id. Is that possible?
I see the following code in the FileManager controller:

public FileManagerController(IHostingEnvironment hostingEnvironment)
        {
            

            this.basePath = hostingEnvironment.ContentRootPath;
            this.operation = new PhysicalFileProvider();
            this.operation.RootFolder(this.basePath + "\\wwwroot\\Files"); // Data\\Files denotes in which files and folders are available.
        }

As you can see, here the root folder path is set to "\\wwwroot\\Files". How do I change this to something else based on a selection made from the client side. For example, if I want to set it to "\\wwwroot\\Client1".  How do I do that? I am using Blazor webassembly.

Regards,
Amjad.



8 Replies 1 reply marked as answer

SP Sowmiya Padmanaban Syncfusion Team January 27, 2021 11:18 AM UTC

Hi Amjad Khan,  
 
Greetings from Syncfsuion support. 
 
We have checked your requirement with FileManager component (setting root folder from client to server). You can pass the additional data (user name ) from client to server by using onSend event.  
 
Please, refer to the below code snippet. 
 
@using Syncfusion.Blazor.FileManager 
 
<div class="control-section"> 
    <SfFileManager TValue="FileManagerDirectoryContent" > 
        <FileManagerEvents TValue="FileManagerDirectoryContent" OnSend="send" ></FileManagerEvents> 
        <FileManagerAjaxSettings Url="/api/Home/FileOperations" 
                                 UploadUrl="/api/Home/Upload" 
                                 DownloadUrl="/api/Home/Download" 
                                 GetImageUrl="/api/Home/GetImage"> 
        </FileManagerAjaxSettings> 
    </SfFileManager> 
</div> 
 
@code { 
    SfFileManager<FileManagerDirectoryContent> filemanager; 
    public void send(Syncfusion.Blazor.FileManager.BeforeSendEventArgs args) 
    {        
            Dictionary<string, object> data = new Dictionary<string, object>(); 
            data.Add("User_name", "Client1"); 
            args.CustomData = data;     
    } 
} 
 
Controller: 
 
public class FileManagerDirectoryContent1 
    { 
        public Dictionary<string, object> CustomData { get; set; } 
       public FileManagerDirectoryContent[] Data { get; set; } 
        public bool ShowHiddenItems { get; set; } 
   } 
  [Route("FileOperations")] 
        public object FileOperations([FromBody] FileManagerDirectoryContent1 args) 
        { 
            username = args.CustomData["User_name"].ToString(); 
            if(username == "Client1") 
            { 
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username); 
            } 
} 
[Route("Upload")] 
        public IActionResult Upload(string path, IList<IFormFile> uploadFiles, string action) 
        { 
            if (username == "Client1") 
            { 
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username); 
            } 
       } 
[Route("Download")] 
        public IActionResult Download(string downloadInput) 
        { 
            if (username == "Client1") 
            { 
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username); 
            }         
} 
        // gets the image(s) from the given path 
        [Route("GetImage")] 
        public IActionResult GetImage(FileManagerDirectoryContent args) 
        { 
            if (username == "Client1") 
            { 
                this.operation.RootFolder(this.basePath + "\\" + "wwwroot\\" + username); 
            } 
       } 
 
Please, refer to the sample link: 
 
 
Please, refer to the below links for more details on FileManager component. 
 
 
 
 
Please let us know, if you need any further assistance. 
 
Regards,  
Sowmiya.P 


Marked as answer

AK Amjad Khan January 27, 2021 04:28 PM UTC

Thanks, this works like a charm.

One more thing, when the FileManager starts, it is not in the details view mode. Can we start in the details view mode instead of the large icon view mode?

Regards,
Amjad.


SP Sowmiya Padmanaban Syncfusion Team January 28, 2021 10:33 AM UTC

Hi Amjad Khan, 
 
Most Welcome.  
 
Yes, you can start with Details view by setting the View property for FileManager component. Please refer to the below code snippet. 
 
<SfFileManager TValue="FileManagerDirectoryContent" View="ViewType.Details"> 
        <FileManagerEvents TValue="FileManagerDirectoryContent" OnSend="send" ></FileManagerEvents> 
        <FileManagerAjaxSettings Url="/api/Home/FileOperations" 
                                 UploadUrl="/api/Home/Upload" 
                                 DownloadUrl="/api/Home/Download" 
                                 GetImageUrl="/api/Home/GetImage"> 
        </FileManagerAjaxSettings> 
    </SfFileManager> 
 
Please, refer to the sample link. 
 
 
Please let us know, if you need any further assistance. 
 
Regards,  
Sowmiya.P 



AG Anthony Griggs August 9, 2022 12:29 PM UTC

I am on version 20.1.0.60 and it doesn't seem as if the args.CustomData exists any longer. I am also using Blazor WASM so a session variable isn't really going to work either. Have you come up with a better method for this yet?



AK Amjad Khan August 9, 2022 04:55 PM UTC

Yes, use the following code in the controller. My root folder is wwwroot/Files/patientid. I set the patient id dynamcially. In the calling component, the patientid is set using the dictionary as follows:

```

public void send(Syncfusion.Blazor.FileManager.BeforeSendEventArgs args)

    {

        Dictionary<string, object> data = new Dictionary<string, object>();

        data.Add("FilePath", "Patient-"+AppState.SelectedPatient.PatientId.ToString());

        args.CustomData = data;

    }

```

Default controller:

```

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Mvc;

using System;

using System.Collections.Generic;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Http.Features;

//File Manager's base functions are available in the below namespace

using Syncfusion.EJ2.FileManager.Base;

//File Manager's operations are available in the below namespace

using Syncfusion.EJ2.FileManager.PhysicalFileProvider;

using Newtonsoft.Json;

using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;


namespace BlazorApp1.Controllers

{

    [Route("api/[controller]")]

    public class DefaultController : Controller

    {

        public PhysicalFileProvider operation;

        public string basePath;

        public static string patientId;


        [Obsolete]

        public DefaultController(IHostingEnvironment hostingEnvironment)

        {

            this.basePath = hostingEnvironment.ContentRootPath;

            this.operation = new PhysicalFileProvider();

            this.operation.RootFolder(this.basePath + "wwwroot/Files"); // Data\\Files denotes in which files and folders are available.


        }


        public class FileManagerDirectoryContent1

        {

            public Dictionary<string, object> CustomData { get; set; }

            public bool HasChild { get; set; }

            public DateTime DateCreated { get; set; }

            public DateTime DateModified { get; set; }

            public string PreviousName { get; set; }


            public FileManagerDirectoryContent[] Data { get; set; }

            public bool ShowHiddenItems { get; set; }

            public string SearchString { get; set; }

            public bool CaseSensitive { get; set; }

            public IList<IFormFile> UploadFiles { get; set; }

            public string[] RenameFiles { get; set; }

            public string TargetPath { get; set; }

            public string ParentId { get; set; }

            public string FilterId { get; set; }

            public string FilterPath { get; set; }

            public string Id { get; set; }

            public string Type { get; set; }

            public bool IsFile { get; set; }


            public long Size { get; set; }

            public string Name { get; set; }

            public string[] Names { get; set; }

            public string NewName { get; set; }

            public string Action { get; set; }

            public string Path { get; set; }

            public FileManagerDirectoryContent TargetData { get; set; }

            public AccessPermission Permission { get; set; }



        }

        // Processing the File Manager operations

        [Route("FileOperations")]

        public object FileOperations([FromBody] FileManagerDirectoryContent1 args)

        {

            string filepath = args.CustomData["FilePath"].ToString(); //file path is the patientid, sent from Patientcabinet.razor

            patientId = filepath;

            string[] paths = { this.basePath, "wwwroot", "Files", filepath };

            string fullPath = Path.Combine(paths);

            Directory.CreateDirectory(fullPath); //will create if dir does not exist

            this.operation.RootFolder(fullPath);




            switch (args.Action)

            {

                // Add your custom action here

                case "read":

                    // Path - Current path; ShowHiddenItems - Boolean value to show/hide hidden items

                    return this.operation.ToCamelCase(this.operation.GetFiles(args.Path, args.ShowHiddenItems));

                case "delete":

                    // Path - Current path where of the folder to be deleted; Names - Name of the files to be deleted

                    return this.operation.ToCamelCase(this.operation.Delete(args.Path, args.Names));

                case "copy":

                    // Path - Path from where the file was copied; TargetPath - Path where the file/folder is to be copied; RenameFiles - Files with same name in the copied location that is confirmed for renaming; TargetData - Data of the copied file

                    return this.operation.ToCamelCase(this.operation.Copy(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));

                case "move":

                    // Path - Path from where the file was cut; TargetPath - Path where the file/folder is to be moved; RenameFiles - Files with same name in the moved location that is confirmed for renaming; TargetData - Data of the moved file

                    return this.operation.ToCamelCase(this.operation.Move(args.Path, args.TargetPath, args.Names, args.RenameFiles, args.TargetData));

                case "details":

                    // Path - Current path where details of file/folder is requested; Name - Names of the requested folders

                    return this.operation.ToCamelCase(this.operation.Details(args.Path, args.Names));

                case "create":

                    // Path - Current path where the folder is to be created; Name - Name of the new folder

                    return this.operation.ToCamelCase(this.operation.Create(args.Path, args.Name));

                case "search":

                    // Path - Current path where the search is performed; SearchString - String typed in the searchbox; CaseSensitive - Boolean value which specifies whether the search must be casesensitive

                    return this.operation.ToCamelCase(this.operation.Search(args.Path, args.SearchString, args.ShowHiddenItems, args.CaseSensitive));

                case "rename":

                    // Path - Current path of the renamed file; Name - Old file name; NewName - New file name

                    return this.operation.ToCamelCase(this.operation.Rename(args.Path, args.Name, args.NewName));

            }

            return null;

        }

        [Route("Download")]

        public IActionResult Download(string downloadInput)

        {

            string[] paths = { this.basePath, "wwwroot", "Files", patientId };

            string fullPath = Path.Combine(paths);

            this.operation.RootFolder(fullPath);


            //Invoking download operation with the required paramaters

            // path - Current path where the file is downloaded; Names - Files to be downloaded;

            FileManagerDirectoryContent args = JsonConvert.DeserializeObject<FileManagerDirectoryContent>(downloadInput);

            return operation.Download(args.Path, args.Names);

        }

        [Route("Upload")]

        public IActionResult Upload(string path, IList<IFormFile> uploadFiles, string action, string CustomData)

        {

            Dictionary<string, object> AjaxSettings = JsonConvert.DeserializeObject<Dictionary<string, object>>(CustomData);

            string patientId = (string)AjaxSettings["FilePath"];


            string[] paths = { this.basePath, "wwwroot", "Files", patientId };

            string fullPath = Path.Combine(paths);

            this.operation.RootFolder(fullPath);



            //Invoking upload operation with the required paramaters

            // path - Current path where the file is to uploaded; uploadFiles - Files to be uploaded; action - name of the operation(upload)

            FileManagerResponse uploadResponse;

            uploadResponse = operation.Upload(path, uploadFiles, action, null);

            if (uploadResponse.Error != null)

            {

                Response.Clear();

                Response.ContentType = "application/json; charset=utf-8";

                Response.StatusCode = Convert.ToInt32(uploadResponse.Error.Code);

                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = uploadResponse.Error.Message;

            }

            return Content("");

        }

        [Route("GetImage")]

        public IActionResult GetImage(FileManagerDirectoryContent1 args, string CustomData)

        {


            string[] paths = { this.basePath, "wwwroot", "Files", patientId };

            string fullPath = Path.Combine(paths);

            this.operation.RootFolder(fullPath);


            //Invoking GetImage operation with the required paramaters

            // path - Current path of the image file; Id - Image file id;

            return this.operation.GetImage(args.Path, args.Id, false, null, null);

        }

        public IActionResult Index()

        {

            return View();

        }

    }

}

```




IL Indhumathy Loganathan Syncfusion Team August 10, 2022 11:13 AM UTC

Hi Anthony,


In Blazor, we have support to send JWT token value for both Read and Upload operation and able to pass custom data for Download and GetImage operation from client to server. You can use this way to send root folder name from client end to server to set it as a root folder.


Similar requirement is achieved in the below Blazor sample. Please find the sample and explanation about the requirement from the below link.


https://github.com/SyncfusionExamples/blazor-filemanager-pass-jwt-token


Please get back to us if you need any further assistance.


Regards,

Indhumathy L



AG Anthony Griggs August 18, 2022 12:51 PM UTC

Thanks for the reply... I get all that and I've implemented as much using the read and upload anyway. The download integration just seems way to heavy so we've instead just changed the tool to use our existing download method. However it would be nice if this functionality could be built in like a property... I had to create custom code to validate the token being sent doing it your suggested way... but it would be nice if it simply used the built in authentication mechanisms by default after all the tool does allow for file system access into a network. It seems like it would have some built in security considerations by default.



IL Indhumathy Loganathan Syncfusion Team August 23, 2022 03:00 PM UTC

Hi Anthony,


As per the current implementation of the File Manager component, the HttpClient instance is only sent in Read and Upload operations since we have handled only those file operations using HTTP requests. You can use the OnSend event to set HttpClientInstance for both Read and Upload operations.


The Download operation of File Manager is handled by using a form submit. We don’t handle it by using HTTP requests, so it is not possible to pass the HttpClientInstance here. However, you can send custom values from client to server for a Download operation. You can prevent our default download operation by setting args.Cancel as true in the BeforeDownload event. Then you can trigger the customized download operation using an interop call where you can pass custom values to the server side, as explained in our previous update.


However, we will take your suggestion into consideration in our future enhancements and will inform you in the future if this scenario is considered in any of our release plans.


Regards,

Indhumathy L


Loader.
Up arrow icon