File exists on the server?

How can I check if the file I want to open (or I want to upload) already exists on the server from a url ?
The following piece of code doesn't work

    protected override void OnInitialized()
    {
        currentUrl = NavigationManager.BaseUri;
        string url = currentUrl + @"files/filename.pdf";
        if (!File.Exists(url))
                /*show error message*/
        else
               await jsRuntime.InvokeAsync<object>("open", url, "_blank");
    }



13 Replies 1 reply marked as answer

SN Sevvandhi Nagulan Syncfusion Team February 16, 2021 01:33 PM UTC

Hi Walter, 
 
Greetings from Syncfusion support. 
 
We checked your query. If the file already exists in server, then add the customer message using header in the server side. We can get the added header along with the text in the success event. Then update that messages to status text. Kindly refer below code. 
 
[SampleDataController.cs] 
 
        [HttpPost("[action]")] 
        public async void Save(IList<IFormFile> UploadFiles) 
        { 
            try 
            { 
                foreach (var file in UploadFiles) 
                { 
                    if (UploadFiles != null) 
                    { 
                        var filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); 
                        filename = hostingEnv.WebRootPath + $@"\{filename}"; 
                        if (!System.IO.File.Exists(filename)) 
                        { 
                            using (FileStream fs = System.IO.File.Create(filename)) 
                            { 
                                file.CopyTo(fs); 
                                fs.Flush(); 
                            } 
                        } 
                        else 
                        { 
                            Response.Clear(); 
                            Response.StatusCode = 204; 
                            Response.Headers.Add("ID", "File already exists.");// Assign the custom data in the response header. 
                            Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File already exists."; 
                        } 
                    } 
                } 
            } 
            catch (Exception e) 
            { 
                Response.Clear(); 
                Response.ContentType = "application/json; charset=utf-8"; 
                Response.StatusCode = 204; 
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload"; 
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message; 
            } 
             
        } 
 
[Index.razor] 
public void OnSuccess(SuccessEventArgs args) 
    { 
         
        //Also, you can send the status from the server in header and receive in the success event 
        var customHeader = args.Response.Headers.Split(new Char[] { '\r' })[1]; // To split the response header values 
        var value = customHeader.Split(new Char[] { ':' })[1].Trim(); // To get the value for the key pair of provided custom data in header 
         if (value.Contains("exists")) 
        { 
            args.StatusText = value; 
        } 
   } 
 
Please find the sample below. 
 
 
Please check the above sample and get back to us if you need further assistance. 
 
Regards, 
Sevvandhi N 



WM Walter Martin February 16, 2021 04:09 PM UTC

I added in my startup.cs file the following lines from your sample but adding them my application doesn't start giving me the error message I share  you in attachment togheter with my startup.cs file

I'm using BoldReports and I suppose there's a sort of incompatibility because without the lines below my application starts

services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
app.UseMvcWithDefaultRoute();



Attachment: Startup_e2458265.zip


WM Walter Martin replied to Walter Martin February 18, 2021 11:29 AM UTC

I added in my startup.cs file the following lines from your sample but adding them my application doesn't start giving me the error message I share  you in attachment togheter with my startup.cs file

I'm using BoldReports and I suppose there's a sort of incompatibility because without the lines below my application starts

services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
app.UseMvcWithDefaultRoute();



Attachment: Startup_e2458265.zip

In this page Add Web Viewer in Blazor application | Bold Reports I see that to use BoldReports libraries it's necessary to add the following lines in the startup.cs 
app.UseEndpoints(endpoints =>
{
  endpoints.MapControllers();
  endpoints.MapBlazorHub();
  endpoints.MapFallbackToPage("/_Host");
})
but the line endpoints.MapControllers(); is in conflict with the use of app.UseMvcWithDefaultRoute();
How can I use both ?


SN Sevvandhi Nagulan Syncfusion Team February 18, 2021 12:58 PM UTC

Hi Walter, 

Bold Reports dependencies do not have any compatibility issues with ASP.Net Core or ASP.Net Web frameworks. As you have mentioned that you are facing this issue with the end points could you please let us know additional details regarding this. Could you please let us know about your project details, regarding your framework version whether it is of ASP.Net Core 3.1 or ASP.Net Core 3.5 or .Net 5. Also, could you please let us know the type of project you are using whether it is of Blazor Web Assembly or of Blazor Server as it will be helpful for us to validate the issue from our end. Also, if possible please share with us the controller file also. 

Regards, 
Sevvandhi N 



WM Walter Martin February 18, 2021 01:28 PM UTC

Thanks for your reply
here is my environment:
I'm using AspNet Core 5.0.2 + Syncfusion Blazor server side version  18.4.0.43 + BoldReports.Net.Core version 2.4.23

In attachment I share you my complete startup.cs file where I recently added these lines to work with the sampledatacontroller you suggested me in this ticket
services.AddMvc(option => option.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
app.UseMvcWithDefaultRoute();

I add you also the BoldReport Controller in attachment

without the last line above, my project works without any error, instead after inserting the last line above, it gives me the error in attachment where there seems to be a conflict between these 2 lines:
  • app.UseMvcWithDefaultRoute();
  • endpoints.MapControllers();
let me know if something is not clear or you need more details.

Thanks in advance





Attachment: Startup_1b93e26d.zip


WM Walter Martin February 22, 2021 10:49 PM UTC

I  changed your sample to add my BoldReportApiController and as you can see the application generates the error when you start it.
If you remove the line 
endpoints.MapControllers();
from startup.cs 
the uploadfile component works but not the BoldReportApi
How can I solve it ?
thanks

Attachment: BlazorApp1_3105804c.zip


SN Sevvandhi Nagulan Syncfusion Team February 23, 2021 10:44 AM UTC

Hi Walter, 


Thanks for providing the sample. 


We changed the routing configuration for API controller instead of using default MVC routing. You can now customize the routing parameter to suit your needs and configure routing using the MapControllerRoute method based on the route template. Please refer to the code below.. Please refer the below code. 


public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
        { 
            if (env.IsDevelopment()) 
            { 
                app.UseDeveloperExceptionPage(); 
            } 
            else 
            { 
                app.UseExceptionHandler("/Error"); 
                app.UseHsts(); 
            } 
 
            app.UseHttpsRedirection(); 
            app.UseStaticFiles(); 
 
            app.UseRouting(); 
        //    app.UseMvcWithDefaultRoute(); 
 
            app.UseEndpoints(endpoints => 
            { 
                endpoints.MapControllerRoute("default", "{controller=SampleData}/{action=Save}"); 
                endpoints.MapBlazorHub(); 
                endpoints.MapFallbackToPage("/_Host"); 
            }); 
        } 





Please find the sample below. 





Please get back to us if you need further assistance. 


Regards, 
Sevvandhi N 


Marked as answer

WM Walter Martin February 23, 2021 02:22 PM UTC

Many thanks for your reply
this is something I should have already known from Microsoft documentation
it works with your suggestion




SN Sevvandhi Nagulan Syncfusion Team February 24, 2021 04:59 AM UTC

Hi Walter, 


Thanks for the update. Please get back to us if you need further assistance. 


Regards, 
Sevvandhi N 



WM Walter Martin February 24, 2021 08:24 PM UTC

How can I get the filename I want to upload in my razor page to save it then in the database table before o after saving the file in the server ?
If I use the SfUploader without the controller, I can get the filename from this piece of code in the ValueChange event

    private void OnChange(UploadChangeEventArgs args)
    {
        foreach (var file in args.Files)
        {
            filename = file.FileInfo.Name;
        }
    }

but if I use the controller, args.Files is null




SN Sevvandhi Nagulan Syncfusion Team February 25, 2021 11:39 AM UTC

Hi Walter, 


We checked your query. You can get the file name in the select event arguments when you using the controller for saving the file. Please refer the below code. 


public void OnSelect(SelectedEventArgs args) 
    { 
        foreach(var file in args.FilesData) 
        { 
            var name = file.Name;  
        } 
         
    } 


Please find the sample below. 




Please check the above sample and get back to us if you need further assistance. 


Regards, 
Sevvandhi N 




WM Walter Martin February 26, 2021 12:12 AM UTC

You're right, many thanks it works
 


SN Sevvandhi Nagulan Syncfusion Team February 26, 2021 05:00 AM UTC

Hi Walter,  


Thanks for the update. Please get back to us if you need further assistance.  


Regards,  
Sevvandhi N 


Loader.
Up arrow icon